import Config from '../../config/appConstants';
import { createRequest } from '../api/helper';
import { store } from '../../redux';
class LandRequestService {
  constructor() {

    this.loginDtls = store.getState().pki_details.hasOwnProperty("OrgUserValidator") ? store.getState().pki_details.OrgUserValidator : store.getState().pki_details;
  }
  async retrieveTemplate(type, isproceedForm) {
    console.log("type and isprocess form",type)
    var API_URL;

      if(isproceedForm) {
              API_URL    = Config.LN1ISPROCEEDFORM;
      } else { 
              switch (type) {
                case "residential":
                  API_URL = Config.LN1RESIDENTS;
                  break;
                case "commercial":
                  API_URL = Config.LN1COMMERCIAL;
                  break;
                case "industrial":
                  API_URL = Config.LN1COMMERCIAL;
                  break;
                  
                case "location-selection":
                    API_URL = Config.LN1LOCATIONSELECTIONFORM;
                break;


                case "residentialpreview":
                  API_URL = Config.LN1RESPREVIEW;
                  break;
                case "residentail-re-submit":
                  API_URL = Config.LN1RE_SUBMIT_PREVIEW;
                  break;
                case "re-submit-residential-form":
                    API_URL = Config.LN1_RE_RES_FORM;
                break;
                case "commercialpreview":
                  API_URL = Config.LN1B_COMMERCIAL;
                  break;
                  case "commercial-editpreview":
                    API_URL = Config.LN1B_EDIT_COMMERCIAL;
                    break;                  
                case "industrialpreview":
                  API_URL = Config.LN1RESCOMMERCIALPREVIEW;
                  break;
                case "applicationPreview":
                  API_URL = Config.LN1APPLICATIONPREVIEW;
                  break;
                case "commercial-re-submit":
                  API_URL = Config.LN1RE_COMMERCIAL_SUBMIT_PREVIEW;
                  break;
                case "re-submit-commercial-form":
                    API_URL = Config.LN1_COMMERCIAL_RE_RES_FORM;
                break;
                case "commercial-company-form":
                  API_URL = Config.LN1_COMMERCIAL_COMPANY_FORM;
                  break;
                case "relationship-details-form":
                  API_URL = Config.LN1_RELATIONSHIP_DETAILS_FORM;
                  break;
                case "commercial-payment-preview":
                  API_URL = Config.LN1_COMMERCIAL_COMPANY_PAYMENT_PREVIEW;
                break;
                case "residential-payment-preview":
                  API_URL = Config.LN1_RESIDENTIAL_COMPANY_PAYMENT_PREVIEW;
                break;
                case "add-display-company":
                  API_URL = Config.LN1COMMERCIALCOMPANYLISTDTLS;
                break;
                case "get-company-info":
                  API_URL = Config.LN1COMMERCIALCOMPANYDTLS;
                break;
                

                default:
                  API_URL = Config.LN1ISPROCEEDFORM;
              }
      }

        if(API_URL) {
            return fetch(API_URL)
              .then(response => {
                if (!response.ok) {
                  this.handleResponseError(response);
                }
                return response.json();
              })
              .then(json => {
                  //console.log('JSON', json);
                //  const items = [];
                //  for (const [index, value] of json.entries()) {
                //     //items.push(<li key={index}>{value}</li>)
                //     items.push(value);
                //   }
                  let response = json;
                  return response;
              })
              .catch(error => {
                this.handleError(error);
              });
        } else {
          console.log('No Valid Request');
        }
  }




  async fetchTemplate(API_URL) {
    
        if(API_URL) {
            return fetch(API_URL)
              .then(response => {
                if (!response.ok) {
                  this.handleResponseError(response);
                }
                return response.json();
              })
              .then(json => {
                  let response = json;
                  return response;
              })
              .catch(error => {
                this.handleError(error);
              });
        } else {
          console.log('No Valid Request');
        }
  }

  async getApplicantData(requestParam) {
        if(requestParam) {
          return fetch(Config.GET_INVOVLED_PARTY + "?CRN="+requestParam.CRN)
            .then(response => {
              if (!response.ok) {
                this.handleResponseError(response);
              }
              return response.json();
            })
            .then(json => {
                console.log('JSON', json);
                let response = json;
                return response;
            })
            .catch(error => {
              this.handleError(error);
            });
        } else {
            console.log('No Valid Request');
        }
  }

 async getLandType(type, serviceSubID) {
 
      // var params = {
      //   ServiceDomain    : type,
      //   ServiceSubId     : serviceSubID,
      
      // };

      var customHeader = '';  

      const afterLoginHeader = {
        'accept': 'application/json',
        'content-type' : 'application/json',
        'RequestID' : (new Date().valueOf()),
        'SessionID' : '',
        'ApplicationID' : 'WEB',
        'ChannelID' : 'WEB',
        'CountryCode' : 'OM',
        'ApplicantType' : 'USER'
      }

      var loginData = store.getState().pki_details.hasOwnProperty("OrgUserValidator") ? store.getState().pki_details.OrgUserValidator :  store.getState().pki_details;
      afterLoginHeader.SessionID = loginData.SessionID;
      customHeader = afterLoginHeader;


      console.log("header section", customHeader);
  


      if(type!=="" && serviceSubID !=="") {
        return fetch(Config.LAND_APPLICABLE_SERVICES + "?ServiceDomain="+type+"&ServiceID="+serviceSubID, customHeader)
          .then(response => {
            if (!response.ok) {
              this.handleResponseError(response);
            }
            return response.json();
          })
          .then(json => {
              console.log('JSON', json);
              let response = json;
              return response;
          })
          .catch(error => {
            this.handleError(error);
          });
      } else {
          console.log('No Valid Request');
      }
      
 }

  async checkApplicantEligibility(state, eServiceId, logInfo) {

          var postData = {
            SessionId     : logInfo.SessionID,
            ServiceId     : eServiceId,
            ServiceSubId  : state.landType,
        };

        var response = this.triggerServiceRequest('GET', Config.ELIGIBILITY_API, postData, 1);

        console.log("+++++++++"+ JSON.stringify(response));
    
  }


  getApplicantDetails(requestData) {

      createRequest('GET',Config.GET_INVOVLED_PARTY + "?CRN="+requestData.CRN,1,'')
      .then((response) => {
        //this.responseData = response.data;

        this.sendPromiseResponse(response.data);
          // console.log("axios:land_service_resp  == "+ this.listArr.length);       
      },(error) => {
          console.log("axios:land_service_error  == "+error);
          // console.log("axios:land_service_status  == "+error.response.statusCode+' :: land:type == '+error.response.type+" :: details == "+error.response.details);
      });  
  }

  sendPromiseResponse(responseData) {
     return responseData;
  }


  async createApplication(frmData) {

    const postData = {
      "ApplicationDetails": {
        "ApplicationData": {
          
          "ServiceSubID": "LN2Z",
          "InvolvedPartyID": 20,
          "SubmissionDateTime": "2020-01-18T14:57:42.624Z",
          "ApplicationStatusID": 10,
          
          "ServiceDeliveryFlag": "Y",
         
          "UserTypeID": 0,
          "Comment": "string",
          "RegionalOfficeID": 2, 
          "PostOfficeID": 2,
          "IsDeleted": "N",
          "CreatedBy": "string",
          "CreatedTimeStamp": "2020-01-18T14:57:42.624Z",
          "UpdatedBy": "string",
          "UpdatedTimeStamp": "2020-01-18T14:57:42.624Z",
          "SourceSystemID": "strin"
        },
        "LandReqApplData": {
          "LandRequestPlace": "string",
          "LandRequestRegionID": "strin",
          "LandRequestWilayatID": "strin",
          "LandRequestVillageID": "strin",
          "LandDrawCounter": 10
          
        },
        "RERequestApplications": {
          
          "NEWSARTICLEDATE": "2020-01-18T14:57:42.625Z",
          "ApplicationReason": "get place",
           "PostOfficeId": 2,
          "RegionalOfficeId": 1,
          "AttorneyId": "1111",
          "FreezeFlag": "N",
          "InvolvedPartyTypeId": 2
          
        },
        "ServiceSubServices": {
        
          "ServiceId": "string",
          "SubServiceNameAr": "string",
          "SubServiceNameEn": "string",
          "IsActive": "Y"
         
        },
        "ApplicationNotesAndAck": {
          
          "AckFlag1": "Y",
          "Note1": "string",
          "Ack_flag2": "Y",
          "Note2": "string"
          
        },
        "ApplicationStatusHistory": {
         
          "ApplicationActionId": 10,
          "ApplicationActionTimestamp": "2020-01-18T14:57:42.625Z",
          "ApplicationActionUser": "strin",
           "ApplicationStatusId": 10,
           "CreatedBy": "string",
          "IsDeleted": "N",
          "CreatedTimeStamp": "2020-01-18T14:57:42.625Z",
          "UpdatedBy": "string",
          "UpdatedTimeStamp": "2020-01-18T14:57:42.625Z"
        }
      }
    };

   
    // Bind values
    
    postData.ApplicationDetails.ApplicationData.RegionalOfficeID = frmData.governorate;
    postData.ApplicationDetails.ApplicationData.PostOfficeID     = frmData.province;
    postData.ApplicationDetails.ApplicationData.CreatedBy        = typeof this.loginDtls == "object" ? this.loginDtls.ApplicantName : "";
    postData.ApplicationDetails.LandReqApplData.LandRequestPlace = frmData.landPlace;
   
    postData.ApplicationDetails.LandReqApplData.LandRequestRegionID     =  frmData.governorate;
    postData.ApplicationDetails.LandReqApplData.LandRequestWilayatID    =  frmData.province;
    postData.ApplicationDetails.LandReqApplData.LandRequestVillageID    =  frmData.village;
   
    
    createRequest('post',Config.APPLICATION_LIST,1,postData).then(
    (response) => {
        return response.data;
    },
    (error) => {
        console.log("axios:login_error  == "+error);    
        return false;        
    });

}


  



async triggerServiceRequest(requestType, requestUrl, requestData, isAuth) {

   
   createRequest(requestType, requestUrl, isAuth, requestData).then(
          (response) => {
              console.log("axios:success  == "+JSON.stringify(response.data));
              return "tester"; //response.data;
          },
          (error) => {
              console.log("axios:error  == "+error);    
              return false;        
          });

     
  }


  
          // triggerServiceRequest(data).then(function(response) {
          //   console.log(response);
          // });


  



  async getItem(itemLink) {
    console.log("ItemService.getItem():");
    console.log("Item: " + itemLink);
    return fetch(itemLink)
      .then(response => {
        if (!response.ok) {
            this.handleResponseError(response);
        }
        return response.json();
      })
      .then(item => {
          item["link"] = item._links.self.href;
          return item;
        }
      )
      .catch(error => {
        this.handleError(error);
      });
  }
  async createItem(newitem) {
    console.log("ItemService.createItem():");
    console.log(newitem);
    return fetch(Config.ITEM_COLLECTION_URL, {
      method: "POST",
      mode: "cors",
      headers: {
            "Content-Type": "application/json"
        },
      body: JSON.stringify(newitem)
    })
      .then(response => {
       if (!response.ok) {
            this.handleResponseError(response);
        }
        return response.json();
      })
      .catch(error => {
        this.handleError(error);
      });
  }
  async deleteItem(itemlink) {
    console.log("ItemService.deleteItem():");
    console.log("item: " + itemlink);
    return fetch(itemlink, {
      method: "DELETE",
      mode: "cors"
    })
      .then(response => {
        if (!response.ok) {
            this.handleResponseError(response);
        }
      })
      .catch(error => {
        this.handleError(error);
      });
  }
  async updateItem(item) {
    console.log("ItemService.updateItem():");
    console.log(item);
    return fetch(item.link, {
      method: "PUT",
      mode: "cors",
      headers: {
            "Content-Type": "application/json"
          },
      body: JSON.stringify(item)
    })
      .then(response => {
        if (!response.ok) {
          this.handleResponseError(response);
        }
        return response.json();
      })
      .catch(error => {
        this.handleError(error);
      });
  }
  handleResponseError(response) {
      throw new Error("HTTP error, status = " + response.status);
  }
  handleError(error) {
      console.log(error.message);
  }  
}
export default LandRequestService;