import { Injectable, Query } from '@angular/core';
import { IQueryState } from '../models/query.state';

@Injectable({
  providedIn: 'root',
})
export class StateSerializerService {

  serialize(queryState: IQueryState): string {

    let state = "";
    state += (queryState.itemCode) ? queryState.itemCode : "";
    state += ";";
    state += (queryState.parentCode) ? queryState.parentCode + ";" + queryState.level.toString() : ";";
    state += ";";
    state += (queryState.itemType) ?  queryState.itemType : "";
    state += ";";
    state += (queryState.query) ? encodeURIComponent( queryState.query ) : "";
    state += ";";
    state += (queryState.tags) ? encodeURIComponent( queryState.tags ) : "";
    state += ";";
    state += (queryState.bboxFilter) ? "1" : "0";
    state += ";";
    state += (queryState.startDate) ? JSON.stringify(queryState.startDate) : "";
    state += ";";
    state += (queryState.endDate) ? JSON.stringify(queryState.endDate) : "";
    state += ";";
    state += (queryState.bboxFilter && queryState.bbox && queryState.bbox.length>0) ? JSON.stringify(queryState.bbox) : "";

    return btoa(state);
  }

  deserialize(queryState: string): IQueryState {
    const state: IQueryState = { itemCode: null, parentCode: null, level: 1, itemType: null, query: null, tags: null, bboxFilter: false, startDate: null, endDate: null,bbox:[] };
    const stateParts = atob(queryState).split(";");
    if (stateParts.length == 10) {
      if (stateParts[0] != "") state.itemCode = stateParts[0];
      if (stateParts[1] != "") {
        state.parentCode = stateParts[1];
        state.level = parseInt(stateParts[2]);
      }
      if (stateParts[3] != "") state.itemType = stateParts[3];
      if (stateParts[4] != "") state.query = decodeURIComponent(stateParts[4]);
      if (stateParts[5] != "") state.tags = decodeURIComponent( stateParts[5]);
      if (stateParts[6] != "") state.bboxFilter = parseInt(stateParts[6]) == 1;
      if (stateParts[7] != "") state.startDate = new Date(Date.parse(JSON.parse(stateParts[7])));
      if (stateParts[8] != "") state.endDate = new Date(Date.parse(JSON.parse(stateParts[8])));
      if (stateParts[9] != "") state.bbox = JSON.parse(stateParts[9]);
    }

    return state;
  }
}
