import EditableInput from './EditableInput';
import PropertyTable from './PropertyTable';

class HTTPClientView {
  constructor(parent, serverManager, apiRequestTabContent, model, index) {
    this.parent = parent;
    this.serverManager = serverManager;
    this.apiRequestTabContent = apiRequestTabContent;
    this.model = model;
    this.index = index;
  }

  init() {
    let me = this;
    this.apiRequestTabContent.append(this.httpApiRequestTemplate(this.model, this.index));
    let pathInput = new EditableInput({
      name: 'path',
      value: this.model.path
    });
    let queryParamTable = new PropertyTable({
      propertyName: 'queryParams',
      properties: this.model.queryParams
    });

    let headerTable = new PropertyTable({
      propertyName: 'headers',
      properties: this.model.headers
    });

    this.apiRequestTabContent.find(`#api_request_${this.model.id}`).find('.api_request_info').find('.path').each(function() {
      pathInput.init(this, (value) => {
        me.model.path = value;
        me.model.queryParams = me.parent.parseParam(me.model.path);
        queryParamTable.setProperties(me.model.queryParams);
        $('span.variable').off('mouseover');
        $('span.variable').off('mouseout');
        document.querySelectorAll('span.variable').forEach(element => {
          let text = element.innerText;
          element.addEventListener('mouseover', () => me.parent.showPopper(element, text));
          element.addEventListener('mouseout', () => me.parent.hidePopper(element));
        });
      });

      $(this).append(`<label>Path</label>`);

      $('span.variable').off('mouseover');
      $('span.variable').off('mouseout');
    });

    queryParamTable.init(this.apiRequestTabContent.find(`#api_request_${this.model.id}`).find('.query_params')[0], (properties) => {
      this.model.queryParams = properties;
      console.log(this.model.queryParams);
      this.buildPath(this.model);
      pathInput.setValue(this.model.path);
      $('span.variable').off('mouseover');
      $('span.variable').off('mouseout');
      document.querySelectorAll('span.variable').forEach(element => {
        let text = element.innerText;
        element.addEventListener('mouseover', () => this.parent.showPopper(element, text));
        element.addEventListener('mouseout', () => this.parent.hidePopper(element));
      });
    });

    headerTable.init(this.apiRequestTabContent.find(`#api_request_${this.model.id}`).find('.request_headers')[0], (properties) => {
      this.model.headers = properties;
      $('span.variable').off('mouseover');
      $('span.variable').off('mouseout');
      document.querySelectorAll('span.variable').forEach(element => {
        let text = element.innerText;
        element.addEventListener('mouseover', () => this.parent.showPopper(element, text));
        element.addEventListener('mouseout', () => this.parent.hidePopper(element));
      });
    });

  }

  buildPath(model) {
    let queryString = model.path.split('?')[0];
    if (model.queryParams.length > 0) {
      queryString += '?';
    }
    for (let i = 0; i < model.queryParams.length; i++) {
      if (!model.queryParams[i].enabled) {
        continue;
      }
      queryString += model.queryParams[i].key + '=' + model.queryParams[i].value;
      if (i < model.queryParams.length - 1) {
        queryString += '&';
      }
    }
    model.path = queryString;
  }

  httpApiRequestTemplate(apiRequest, index) {
    return `
        <div class="tab-pane fade mt-1 api_request" id="api_request_${apiRequest.id}" style="height: 100%;">
            <div><span class="collection_name">${apiRequest.collectionName}</span> &gt; <span class="api_name">${apiRequest.name}</span></div>
            <div class="d-flex api_request_info">
                <div class="form-floating">
                    <select name="method" class="form-select method" style="width: 90px; border-bottom-right-radius: 0;border-top-right-radius: 0;">
                        <option value="POST"    ${apiRequest.method === 'POST' ? 'selected' : ''}>POST</option>
                        <option value="GET"     ${apiRequest.method === 'GET' ? 'selected' : ''}>GET</option>
                        <option value="PUT"     ${apiRequest.method === 'PUT' ? 'selected' : ''}>PUT</option>
                        <option value="DELETE"  ${apiRequest.method === 'DELETE' ? 'selected' : ''}>DELETE</option>
                        <option value="CONNECT" ${apiRequest.method === 'CONNECT' ? 'selected' : ''}>CONNECT</option>
                        <option value="HEAD"    ${apiRequest.method === 'HEAD' ? 'selected' : ''}>HEAD</option>
                        <option value="OPTIONS" ${apiRequest.method === 'OPTIONS' ? 'selected' : ''}>OPTIONS</option>
                        <option value="TRACE"   ${apiRequest.method === 'TRACE' ? 'selected' : ''}>TRACE</option>
                        <option value="PATCH"   ${apiRequest.method === 'PATCH' ? 'selected' : ''}>PATCH</option>
                    </select>
                    <label class="form-label must">Method</label>
                </div>
                <div class="form-floating">
                    ${this.serverManager.renderHttpServers(apiRequest.server)}
                    <label class="form-label must">Server</label>
                </div>
                <div class="form-floating">
                    <input type="text" name="basePath" class="form-control" style="width: 180px; border-radius: 0" value="${this.serverManager.basePath(apiRequest.server)}" readonly>
                    <label class="must">기본 경로</label>
                </div>
                <div class="form-floating editableInput me-1 path" data-name="path" data-label="Path">                       
                    <label>Path</label>
                </div>
                <button class="btn btn-primary send me-1">Send</button>
                <button class="btn btn-primary save" data-index="${index}" style="height: 58px;">저장</button>
            </div>
            <div class="api_request d-flex flex-column" style="height:100%;">
              <div class="api_request_body">
                <ul class="nav nav-tabs mt-1" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link btn_request_body_tab" data-bs-toggle="tab"
                                type="button" role="tab" aria-controls="requestBody" data-bs-target="#requestBodyTab_${apiRequest.id}"
                                aria-selected="false">Body
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link btn_request_param_tab" data-bs-toggle="tab" 
                                type="button" role="tab" aria-controls="paramTab" data-bs-target="#requestParamTab_${apiRequest.id}"
                                aria-selected="true">Param
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link btn_request_header_tab" data-bs-toggle="tab"
                                type="button" role="tab" aria-controls="requestHeader" data-bs-target="#requestHeaderTab_${apiRequest.id}"
                                aria-selected="false">Header
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link btn_prerequest_tab" data-bs-toggle="tab"
                                type="button" role="tab" aria-controls="preScrit" data-bs-target="#preRequestTab_${apiRequest.id}"
                                aria-selected="false">Pre-Request
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link btn_postrequest_tab" data-bs-toggle="tab"
                                type="button" role="tab" aria-controls="postScript" data-bs-target="#postRequestTab_${apiRequest.id}"
                                aria-selected="false">Post-Request
                        </button>
                    </li>
                </ul>
                <div class="tab-content" style="height: 100%;">
                    <div class="tab-pane fade show request_param_tab" role="tabpanel" id="requestParamTab_${apiRequest.id}" aria-labelledby="requestParams-tab">
                         <div class="query_params">
                         </div> 
                    </div>
                    <div class="tab-pane fade request_header_tab" role="tabpanel" id="requestHeaderTab_${apiRequest.id}"
                         aria-labelledby="requestHeader-tab">
                         <div class="request_headers">
                         </div>
                    </div>
                    <div class="tab-pane fade request_body_tab" role="tabpanel" id="requestBodyTab_${apiRequest.id}" aria-labelledby="requestBody-tab">
                      <div class="d-flex flex-column">
                        <select class="form-select mt-1 request_body_type" name="request_type">
                            <option value="json">json</option>
                            <option value="xml">xml</option>
                            <option value="">text/plain</option>
                        </select>
                        <div class="request_body mt-1" style="width:100%;height: 300px; border:1px solid grey;"></div>
                      </div>
                    </div>
                    <div class="tab-pane fade pre_script_tab" role="tabpanel" id="preRequestTab_${apiRequest.id}" aria-labelledby="preScrit-tab">
                        <div class="d-flex flex-row">
                            <div style="width:calc(100% - 200px);">
                                <div class="pre-request mt-1" style="height:300px;border:1px solid grey;"></div>
                            </div>
                            <div style="width: 200px;">
                                <div class="pre-request-variable">
                                </div>
                            </div> 
                        </div>
                    </div>
                    <div class="tab-pane fade post_script_tab" role="tabpanel" id="postRequestTab_${apiRequest.id}"
                         aria-labelledby="postScrit-tab">
                         <div class="d-flex flex-row">
                           <div style="width:calc(100% - 200px);">
                             <div class="post-request mt-1" style="height:300px;border:1px solid grey;"></div>
                           </div>
                           <div style="width: 200px;">
                             <div class="post-request-variable">
                             </div>
                           </div> 
                        </div>
                    </div>
                </div>
              </div>
              <div class="api_response" style="flex: 1">
                <div class="mt-1">
                  <span>Response</span>
                  <span class="response_status"></span>
                  <span class="response_time"></span>
                  <span class="response_size"></span>
                </div>
                <ul class="nav nav-tabs mt-1" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#responseBodyTab_${apiRequest.id}" type="button" role="tab" aria-controls="responseBody" aria-selected="false">Body</button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" data-bs-toggle="tab" data-bs-target="#responseHeaderTab_${apiRequest.id}" type="button" role="tab" aria-controls="responseHeader" aria-selected="false">Header</button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" data-bs-toggle="tab" data-bs-target="#consoleTab_${apiRequest.id}" type="button" role="tab" aria-controls="consoleTab" aria-selected="false">Console</button>
                    </li>
                </ul>
                <div class="tab-content border-bottom" style="min-height: 250px;">
                  <div class="tab-pane fade show active" id="responseBodyTab_${apiRequest.id}" role="tabpanel"
                       aria-labelledby="responseParams-tab">
                      <div class="response_body mt-1" style="width:100%;height:250px;border:1px solid grey;"></div>
                  </div>
                  <div class="tab-pane fade" id="responseHeaderTab_${apiRequest.id}" role="tabpanel"
                       aria-labelledby="responseParams-tab">
                      <table class="table">
                          <thead>
                          <tr>
                              <th scope="col">이름</th>
                              <th scope="col">값</th>
                          </tr>
                          </thead>
                          <tbody class="response_headers">
                          </tbody>
                      </table>
                  </div>
                  <div class="tab-pane fade" id="consoleTab_${apiRequest.id}" role="tabpanel"
                       aria-labelledby="console-tab">
                      <div class="console mt-1" style="width:100%;height:250px;border:1px solid grey;"></div>
                  </div>
                </div>
            </div>
            </div>
        </div>
       
        `;
  }
}

export default HTTPClientView;
