import EditableInput from './EditableInput';
import APIClient from '../APIClient';

class ServerManager {
  constructor(servers) {
    this.servers = servers || [];
    this.apiClient = new APIClient();
  }

  basePath(serverId) {
    if (serverId === undefined || serverId === null || serverId === '') {
      return '';
    }
    return this.servers.filter(server => server.id == serverId)[0].basePath; // == : 타입 비교 없이 값만 비교
  }

  getServer(serverId) {
    return this.servers.filter(server => server.id == serverId)[0];
  }

  renderServers(selectedServer) {
    const optionsHtml = this.servers.map(server => `<option value="${server.id}" ${selectedServer === server.id ? 'selected' : ''}  data-path="${server.basePath}">${server.name}</option>`).join('');

    return `<select class="form-select server" name="server" style="width: 180px; border-radius: 0;" required>
                <option value="">서버 선택</option>
                ${optionsHtml}</select>`;
  }

  renderTcpServers(selectedServer) {
    const optionsHtml = this.servers.filter(server => server.scheme === 'tcp').map(server => `<option value="${server.id}" ${selectedServer == server.id ? 'selected' : ''}>${server.name}</option>`).join('');

    return `<select class="form-select server" name="server" style="width: 180px; border-radius: 0;" required>
                <option value="">서버 선택</option>
                ${optionsHtml}</select>`;
  }


  getHeader(headers, key) {
    if (headers === undefined || headers === null) {
      return '';
    }

    // Filter the headers to find the matching key
    const filteredHeaders = headers.filter(header => header.key === key);

    // Check if any header was found that matches the key
    if (filteredHeaders.length === 0) {
      console.log('new header');
      let newHeader = { key: key, value: '', enabled : true };
      headers.push(newHeader);
      return newHeader;
    }
    // Return the value of the first matching header
    return filteredHeaders[0];
  }

  renderTcpServerOptions(target, serverOptions, headers, parent) {
    console.log(headers);

    let tableHTML = `
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>Option Key</th>
                    <th>Option Name</th>
                    <th>Offset</th>
                    <th>Length</th>
                    <th>Value</th>
                </tr>
            </thead>
            <tbody>
                ${serverOptions.map(option => `
                    <tr>
                        <td><span>${option.optionKey}</span></td>
                        <td><span>${option.optionName}</span></td>
                        <td><span>${option.offset}</span></td>
                        <td><span>${option.length}</span></td>
                        <td>
                          <div class="editable" data-name="${option.optionKey}" data-value="${this.getHeader(headers, option.optionKey).value}"></div>
                        </td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    `;

    const container = document.querySelector(target);
    container.innerHTML += tableHTML;

    container.querySelectorAll('.editable').forEach(editableElement => {
      const editableInput = new EditableInput({
        name: editableElement.dataset.name,
        value: editableElement.dataset.value
      });

      editableInput.init(editableElement, (value) => {
        let header = this.getHeader(headers, editableElement.dataset.name);
        header.value = value;
        console.log({value});
        console.log(header);

        $('span.variable').off('mouseover');
        $('span.variable').off('mouseout');
        document.querySelectorAll('span.variable').forEach(element => {
          let text = element.innerText;
          element.addEventListener('mouseover', () => parent.showPopper(element, text));
          element.addEventListener('mouseout', () => parent.hidePopper(element));
        });
      });
    });
  }

  renderHttpServers(selectedServer) {
    const optionsHtml = this.servers.filter(server => server.scheme !== 'tcp').
    map(server => `<option value="${server.id}" ${selectedServer === server.id ? 'selected' : ''}  data-path="${server.basePath}">${server.name}</option>`).
    join('');

    return `<select class="form-select server" name="server" style="width: 180px; border-radius: 0;" required>
                <option value="">서버 선택</option>
                ${optionsHtml}</select>`;
  }

  async fillPadding(apiRequest, value, dataLength) {
    let paddedValue = await this.apiClient.processPreScriptAndVariables(apiRequest, value);

    while (paddedValue.length < dataLength) {
      paddedValue = ' ' + paddedValue; // Prepend a space character to the string
    }

    return paddedValue;
  }

  async renderServerPrefix(serverOptions, apiRequest) {
    let message = '';
    for (let i = 0; i < serverOptions.length; i++) {
      //header 에서 값을 가져와야 함.
      let value = '';
      let found = apiRequest.headers.filter(header => header.key === serverOptions[i].optionKey);
      if (found.length > 0) {
        value = found[0].value;
      }

     message += await this.fillPadding(apiRequest, value, serverOptions[i].length);
    }
    return message;
  }
}

export default ServerManager;
