'use strict';

const httpService = require('./httpService-d2e7bf8f.js');
const auth_store = require('./auth.store-1e630a7d.js');
const util = require('./util-47e320b2.js');

const { state, onChange } = auth_store.createStore({
  goals: [],
  goalsLoading: false,
  goalLoading: false
});
const goalStore = { state, onChange };

class AppDataService {
  constructor() { }
  static getInstance() {
    if (!AppDataService.instance) {
      AppDataService.instance = new AppDataService();
    }
    return AppDataService.instance;
  }
  async getAllAppData(appId) {
    let result = await httpService.HttpService.http.get(`api/v1/AppData/${appId}`);
    return result;
  }
  async createAppData(payload) {
    let result = await httpService.HttpService.http.post(`api/v1/AppData/`, payload);
    return result;
  }
  async updateAppData(payload) {
    let result = await httpService.HttpService.http.put(`api/v1/AppData/${payload.Id}`, payload);
    return result;
  }
  async getAllGoals() {
    goalStore.state.goalsLoading = true;
    let result = await this.getAllAppData(util.SparkleGlobal.MY_GOALS_APP_ID);
    if (result) {
      goalStore.state.goals = result.Data.map(item => {
        return Object.assign(Object.assign({}, item), { AppData: JSON.parse(item.AppJsonData) });
      });
      goalStore.state.goalsLoading = false;
    }
    return result;
  }
  async createGoal(payload) {
    goalStore.state.goalLoading = true;
    let result = await this.createAppData(payload);
    if (result) {
      result.Data.AppData = JSON.parse(result.Data.AppJsonData);
      goalStore.state.goals = [...goalStore.state.goals, result.Data];
      goalStore.state.goalLoading = false;
    }
    return result;
  }
  async updateGoal(payload) {
    goalStore.state.goalLoading = true;
    let result = await this.updateAppData(payload);
    if (result) {
      result.Data.AppData = JSON.parse(result.Data.AppJsonData);
      goalStore.state.goals = goalStore.state.goals.map(item => {
        if (item.Id == result.Data.Id) {
          return Object.assign(Object.assign({}, result.Data), { AppData: JSON.parse(result.Data.AppJsonData) });
        }
        return item;
      });
      goalStore.state.goalLoading = false;
    }
    return result;
  }
}

exports.AppDataService = AppDataService;
exports.goalStore = goalStore;
