const isShowRoute = (registryRoute) => {
  if(registryRoute && registryRoute.hasOwnProperty('before')) {
    if(registryRoute.action.showOnSave == 'true') return true;
    if(registryRoute.after.showOnSave == 'true') return true;
    if(registryRoute.before.showOnSave == 'true') return true;
    return false;
  }
  return false;
}

const parseRouteData = data => {
  const removeUserName = items => {
    for(let i = 0; i < items.length; i++) {
      items[i].users.forEach(user => {
        delete user["userName"];
      });
    }
    return items;
  }

  const result = {
    before: {
      routeID: data.before.routeID,
      items: removeUserName(data.before.items)
    },
    after: {
      routeID: data.after.routeID,
      items: removeUserName(data.after.items)
    }
  }
  return JSON.stringify(result);
}

this.StartRegistryRoute = class {
  constructor(_doc) {
    this._doc = _doc;

    this.init();
  }

  async startRoute() {
    Cons.showLoader();
    try {
      const param = new URLSearchParams();

      param.append("data", parseRouteData(this.registryRoute));
      param.append("dataUUID", this.dataUUID);
      param.append("documentID", this.documentID);
      param.append("registryID", this.registryInfo.registryID);
      param.append("subject", this.documentName);
      param.append("type", "ACTIVATE");

      const {login, password} = Cons.creds;
      const url = `../Synergy/rest/api/registry/route/start?locale=${AS.OPTIONS.locale}`;
      const headers = new Headers();
      headers.append("Authorization", "Basic " + btoa(unescape(encodeURIComponent(`${login}:${password}`))));
      headers.append("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
      const response = await fetch(url, {method: 'POST', headers, body: param});

      if(!response.ok) throw new Error(await response.text());

      const result = await response.json();
      if(result.hasOwnProperty('errorCode') && result.errorCode != 0) throw new Error(result.errorMessage);

      Cons.hideLoader();
      this.closeDocument(this._doc);

    } catch (err) {
      Cons.hideLoader();
      UIkit.notification.closeAll();
      showMessage(i18n.tr(err.message), 'error');
      console.log(err);
    }
  }

  init(){
    try {
      const {registryInfo, registryRoute, documentID, dataUUID, documentName, closeDocument} = this._doc;
      this.registryInfo = registryInfo;
      this.registryRoute = registryRoute;
      this.documentID = documentID;
      this.dataUUID = dataUUID;
      this.documentName = documentName;
      this.closeDocument = closeDocument;

      console.log('startRegistryRoute', {
        _doc: this._doc
      });

      if(isShowRoute(registryRoute)) {
        console.log('рисуем окно с маршрутами');
      } else {
        this.startRoute();
      }

    } catch (err) {
      UIkit.notification.closeAll();
      showMessage(i18n.tr(err.message), 'error');
      console.log(err);
    }
  }
}
