import { D as DataModel } from './data-model-f7ccf826.js';
import { n as notImplemented, u as unauthorized, a as notFound } from './utils-7adf28a3.js';
import { U as User } from './User-9f1f4513.js';
import { a as STORAGE_KEY_KIMLIK_USER_ID, S as STORAGE_KEY_KIMLIK_TOKEN } from './kimlik-api-66e341bd.js';
import { U as UserSettings } from './UserSettings-27df01e6.js';
import { i as iterateMinutes } from './date-utils-49551969.js';
import { M as Membership } from './membership-24db029a.js';

class InstanceStorage {
  constructor(prefix, logger) {
    this.data = {};
    // private getData = () => JSON.parse(window.sessionStorage.getItem(this.prefix) || '{}');
    this.getData = () => this.data;
    // private setData = (data: any) => window.sessionStorage.setItem(this.prefix, JSON.stringify(data));
    this.setData = (data) => this.data = data;
    this.prefix = prefix;
    this.logger = logger.new('InstanceStorage').setColor('sun');
  }
  save(key, value) {
    this.logger.debugGroup('save', { key, value, data: this.getData() });
    const data = this.getData();
    data[key] = value;
    this.setData(data);
  }
  get(key) {
    this.logger.debugGroup('get', { key, value: this.getData()[key], data: this.getData() });
    return this.getData()[key];
  }
  remove(key) {
    this.logger.debugGroup('remove', { key, data: this.getData() });
    const data = this.getData();
    delete data[key];
    this.setData(data);
  }
  clear() {
    this.logger.debugGroup('clear', { data: this.getData() });
    this.setData({});
  }
  getAll() {
    this.logger.debugGroup('getAll', { data: this.getData() });
    return this.getData();
  }
}

class AtamaApiDemo {
  constructor(database, logger) {
    this.logger = logger.new('AtamaApiDemo').setColor('carrot');
    this.database = database;
  }
  addAuthInterceptor(token) {
    this.logger.debugGroup('addAuthInterceptor', token);
  }
  getPairsOfUser(base, collection, userRefFieldId, userRefFieldValue) {
    this.logger.debugGroup('getPairsOfUser', { base, collection, userRefFieldId, userRefFieldValue });
    const table = this.database[collection];
    if (!table) {
      this.logger.warnGroup('getPairsOfUser: table not found', { base, collection, userRefFieldId, userRefFieldValue });
      return Promise.reject(`AtamaApiDemo.getPairsOfUser: Table "${collection}" not found`);
    }
    const results = Object.keys(table).map(id => table[id]).filter(m => m[userRefFieldId][0]._id === userRefFieldValue);
    return Promise.resolve({
      results,
      meta: { total: results.length, base }
    });
  }
  // TODO make this function use the actual parameters to return this demo data
  getSelectionList(base, collection, pairConfigId, userRefFieldId, memberToViewRefFieldId) {
    this.logger.debugGroup('getSelectionList', { base, collection, pairConfigId, userRefFieldId, memberToViewRefFieldId });
    // return all mentees directly
    return Promise.resolve({
      results: Object.keys(this.database.uyeMembershipsMentors).map(id => this.database.uyeMembershipsMentors[id]),
      meta: { total: 2, base, query: {} }
    });
  }
  // TODO make this function use the actual parameters to return this demo data
  getSentRequests(base, collection, userRefFieldValue) {
    this.logger.debugGroup('getSentRequests', { base, collection, userRefFieldValue });
    return new Promise(resolve => {
      setTimeout(() => {
        resolve({
          results: Object.keys(this.database.uyeMembershipsMentors)
            .map(id => this.database.uyeMembershipsMentors[id])
            .map((m, i) => DataModel.decode({
            status: i % 2 == 0 ? 'pending' : 'rejected',
            sentTo: User.decode(m.user),
          })),
          meta: { total: 2 }
        });
      }, 200);
    });
  }
  // TODO make this function use the actual parameters to return this demo data
  getReceivedRequests(base, collection) {
    this.logger.debugGroup('getReceivedRequests', { base, collection });
    return new Promise(resolve => {
      setTimeout(() => {
        resolve({
          results: Object.keys(this.database.uyeMembershipsMentors)
            .map(id => this.database.uyeMembershipsMentors[id])
            .map((m, i) => DataModel.decode({
            status: i % 2 == 0 ? 'pending' : 'rejected',
            sentTo: User.decode(m.user),
          })),
          meta: { total: 2 }
        });
      }, 200);
    });
  }
  getMeetingsOfUser(base, collection, structureId, userRefFieldValue) {
    this.logger.debugGroup('getMeetingsOfUser', { base, collection, structureId, userRefFieldValue });
    return Promise.reject(notImplemented('getMeetingsOfUser'));
  }
  endPair(base, collection, pairId) {
    // console.log(base, collection, userRefFieldId, userRefFieldValue);
    this.logger.debugGroup('endPair', { base, collection, pairId });
    return Promise.reject(notImplemented('endPair'));
  }
  sendPairRequest(base, collection, userRefFieldId, userRefFieldValue, memberToViewRefFieldId, memberToViewData) {
    this.logger.debugGroup('sendPairRequest', { base, collection, userRefFieldId, userRefFieldValue, memberToViewRefFieldId, memberToViewData });
    return Promise.reject(notImplemented('sendPairRequest'));
  }
  acceptPairRequest(base, collection, requestId) {
    this.logger.debugGroup('acceptPairRequest', { base, collection, requestId });
    return Promise.reject(notImplemented('acceptPairRequest'));
  }
  rejectPairRequest(base, collection, requestId) {
    this.logger.debugGroup('rejectPairRequest', { base, collection, requestId });
    return Promise.reject(notImplemented('rejectPairRequest'));
  }
}

class DataApiDemo {
  constructor(database, logger) {
    this.get = (collection, id, query) => {
      this.logger.debugGroup('get', { collection, id, query });
      const table = this.database[collection];
      if (!table) {
        this.logger.warnGroup('get: table not found', { collection, id, query });
        return Promise.reject(`DataApiDemo.query: Table "${collection}" not found`);
      }
      const item = table[id];
      if (!item) {
        this.logger.warnGroup('get: item not found', { collection, id, query });
        return Promise.reject(`DataApiDemo.query: Item "${item}" in "${collection}" not found`);
      }
      return Promise.resolve(item);
    };
    this.logger = logger.new('DataApiDemo').setColor('river');
    this.database = database;
  }
  addAuthInterceptor(token) {
    this.logger.debugGroup('addAuthInterceptor', token);
  }
  query(collection, query) {
    this.logger.debugGroup('query', { collection, query });
    const table = this.database[collection];
    if (!table) {
      this.logger.warnGroup('query: table not found', { collection, query });
      return Promise.reject(`DataApiDemo.query: Table "${collection}" not found`);
    }
    return Promise.resolve({
      results: Object.keys(table).map(id => table[id]).filter(m => m.config.name === collection),
      meta: { total: 2, query }
    });
  }
  update(_collection, _id, _body) {
    return Promise.reject({ status: 418 });
  }
}

function findUserWithEmail(database, email) {
  const userId = Object.keys(database.kimlikUsers).find(id => database.kimlikUsers[id].email === email);
  return database.kimlikUsers[userId];
}
class KimlikApiDemo {
  constructor(database, storage, logger) {
    this.logger = logger.new('KimlikApiDemo').setColor('emerald');
    this.storage = storage;
    this.database = database;
  }
  activateUser(email, firstName, lastName, password) {
    this.logger.debugGroup('activateUser', { email, firstName, lastName, password });
    const user = findUserWithEmail(this.database, email);
    user.status = 'active';
    user.firstName = firstName;
    user.lastName = lastName;
    // update user in database
    this.database.kimlikUsers[user._id] = user;
    this.storage.save(STORAGE_KEY_KIMLIK_USER_ID, user._id);
    this.storage.save(STORAGE_KEY_KIMLIK_TOKEN, `${user._id}-token`);
    return Promise.resolve({
      userId: user._id,
      jwt: `${user._id}-token`
    });
  }
  addAuthInterceptor(_token) {
    this.logger.debugGroup('addAuthInterceptor');
  }
  login(email, password) {
    if (password !== 'asdasd') {
      this.logger.errorGroup('login: password mismatch', { email, password });
      return Promise.reject(unauthorized());
    }
    const user = findUserWithEmail(this.database, email);
    if (user) {
      this.storage.save(STORAGE_KEY_KIMLIK_USER_ID, user._id);
      this.storage.save(STORAGE_KEY_KIMLIK_TOKEN, `${user._id}-token`);
      return Promise.resolve({
        userId: user._id,
        jwt: `${user._id}-token`
      });
    }
    this.logger.warnGroup('login: user not found', { email, password });
    return Promise.reject(unauthorized());
  }
  logout() {
    this.logger.debug('logout');
    this.storage.clear();
    return Promise.resolve({});
  }
  register(email, firstName, lastName, password) {
    this.logger.debugGroup('register', { email, firstName, lastName, password });
    return Promise.reject(notImplemented('register'));
  }
  getSession() {
    const token = this.storage.get(STORAGE_KEY_KIMLIK_TOKEN);
    this.logger.debugGroup('getSession', { token, storage: this.storage.getAll() });
    const userId = token.split('-')[0];
    const user = this.database.kimlikUsers[userId];
    if (user) {
      return Promise.resolve({ user, settings: UserSettings.decode({}) });
    }
    this.logger.errorGroup('getSession: user not found', { token, user });
    return Promise.reject(unauthorized());
  }
  getUsers() {
    return Promise.reject('not-implemented');
  }
  getApiKeys() {
    return Promise.reject('not-implemented');
  }
  createApiKey(_data) {
    return Promise.reject('not-implemented');
  }
  deleteApiKey(_id) {
    return Promise.reject('not-implemented');
  }
  updateApiKey(_id, _data) {
    return Promise.reject('not-implemented');
  }
  getSAMLConfigs() {
    return Promise.reject('not-implemented');
  }
  createSAMLConfig(_data) {
    return Promise.reject('not-implemented');
  }
  deleteSAMLConfig(_id) {
    return Promise.reject('not-implemented');
  }
  updateSAMLConfig(_id, _data) {
    return Promise.reject('not-implemented');
  }
}

class TakvimApiDemo {
  // private storage: Storage;
  constructor(database, _storage, logger) {
    this.logger = logger.new('TakvimApiDemo').setColor('asphalt');
    // this.storage = storage;
    this.database = database;
  }
  getCalendarConfig(id) {
    const item = this.database.takvimCalendarConfigs[id];
    if (!item) {
      this.logger.warnGroup('getCalendarConfig: calendar config not found', { id });
      return Promise.reject(`TakvimApiDemo.getCalendarConfig: Calendar config "${id}" not found`);
    }
    return new Promise((resolve => {
      setTimeout(() => resolve(item), 1000);
    }));
  }
  getMeetingsForCalendar(_calendarConfigId, _startDate, _endDate) {
    return Promise.resolve(undefined);
  }
  // getAvailabilities(calendarConfigId: string): Promise<GetListResponse<Availability>> {
  //   const userId = this.storage.get(STORAGE_KEY_KIMLIK_USER_ID);
  //   const user = this.database.kimlikUsers[userId];
  //   if (!user) {
  //     this.logger.warnGroup('getAvailabilities: user not found', { userId, calendarConfigId });
  //     return Promise.reject(notFound());
  //   }
  //
  //   const table = this.database[calendarConfigId];
  //   if (!table) {
  //     this.logger.warnGroup(
  //       'getAvailabilities: table not found',
  //       { calendarConfigId },
  //     );
  //
  //     return Promise.reject(`TakvimApiDemo.getAvailabilities: Table "${calendarConfigId}" not found`);
  //   }
  //
  //   const items = Object.keys(table).map(id => table[id]) as Availability[];
  //   const results = items.filter(item => item.user._id === userId);
  //
  //   this.logger.debugGroup(
  //     'getAvailabilities',
  //     { calendarConfigId, results },
  //   );
  //
  //   return Promise.resolve({ results });
  // }
  getAvailabilitiesOfUser(userId) {
    const user = this.database.kimlikUsers[userId];
    if (!user) {
      this.logger.warnGroup('getAvailabilities: user not found', { userId });
      return Promise.reject(notFound());
    }
    const table = this.database.takvimAvailabilities;
    if (!table) {
      this.logger.warnGroup('getAvailabilities: table "takvimAvailabilities" not found');
      return Promise.reject(`TakvimApiDemo.getAvailabilities: Table "takvimAvailabilities" not found`);
    }
    const items = Object.keys(table).map(id => table[id]);
    const results = items.filter(item => item.user._id === userId);
    this.logger.debugGroup('getAvailabilitiesOfUser', { results, userId });
    return Promise.resolve({ results });
  }
  getUnavailabilitiesOfUser(_calendarConfigId, userId, startTime, _endTime) {
    console.log('userId', userId);
    if (userId === 'kimlikUsers1') {
      return new Promise((resolve => {
        setTimeout(() => resolve({
          results: [
            {
              startDate: '2021-05-02T12:00:00Z',
              endDate: '2021-05-02T13:30:00Z',
              reason: {
                source: 'google-calendar',
                name: 'Family Lunch'
              }
            }
          ]
        }), 200);
      }));
    }
    const morningStart = new Date(startTime);
    morningStart.setHours(7);
    morningStart.setMinutes(0);
    const morningEnd = iterateMinutes(morningStart, 120);
    const noonStart = new Date(startTime);
    noonStart.setHours(12);
    noonStart.setMinutes(0);
    const noonEnd = iterateMinutes(noonStart, 60);
    const eveningStart = new Date(startTime);
    eveningStart.setHours(18);
    eveningStart.setMinutes(0);
    const eveningEnd = iterateMinutes(eveningStart, 60);
    return new Promise((resolve => {
      setTimeout(() => resolve({
        results: [
          {
            startDate: morningStart.toISOString(),
            endDate: morningEnd.toISOString(),
          },
          {
            startDate: noonStart.toISOString(),
            endDate: noonEnd.toISOString(),
          },
          {
            startDate: eveningStart.toISOString(),
            endDate: eveningEnd.toISOString(),
          },
        ]
      }), 300);
    }));
  }
  getMeetingsOfUser(calendarConfigId, guestIDs) {
    const [userId, otherGuestId] = guestIDs;
    const table = this.database.takvimEvents;
    if (!table) {
      this.logger.warnGroup('getMeetingsOfUser: table not found', { calendarConfigId, userId, otherGuestId });
      return Promise.reject(`TakvimApiDemo.getMeetingsOfUser: Table "takvimEvents" not found`);
    }
    const items = Object.keys(table).map(id => table[id]);
    const results = items.filter(item => {
      const hasUser = item.guests.some(guest => guest._id == userId);
      if (!hasUser)
        return false;
      if (!otherGuestId)
        return hasUser;
      const hasOtherUser = item.guests.some(guest => guest._id == userId);
      return hasUser && hasOtherUser;
    });
    this.logger.debugGroup('getMeetingsOfUser', { calendarConfigId, userId, otherGuestId, results });
    return Promise.resolve({ results });
  }
  createMeeting(meeting) {
    this.logger.warnGroup('createMeeting - NOT IMPLEMENTED', { meeting });
    return Promise.resolve({});
  }
  createAvailability(availability) {
    this.logger.warnGroup('createAvailability - NOT IMPLEMENTED', { availability });
    return Promise.resolve({});
  }
  updateAvailability(availability) {
    this.logger.warnGroup('updateAvailability - NOT IMPLEMENTED', { availability });
    return Promise.resolve({});
  }
  deleteAvailability(id) {
    this.logger.warnGroup('deleteAvailability - NOT IMPLEMENTED', { id });
    return Promise.resolve({});
  }
}

class AgreementConsent extends DataModel {
  static decode(json) {
    return Object.assign(Object.create(AgreementConsent.prototype), json);
  }
}

class UyeApiDemo {
  constructor(database, storage, logger) {
    this.logger = logger.new('UyeApiDemo').setColor('river');
    this.database = database;
    this.storage = storage;
  }
  getAppConfigOfMembership(id) {
    this.logger.debugGroup('getAppConfigOfMembership', id);
    for (let i = 0; i < Object.keys(this.database.dvnAppConfigs).length; i++) {
      const key = Object.keys(this.database.dvnAppConfigs)[i];
      if (this.database.dvnAppConfigs[key].membership._id === id) {
        return Promise.resolve(this.database.dvnAppConfigs[key]);
      }
    }
    this.logger.error('getAppConfigOfMembership', 'not-found');
    return Promise.reject({ status: 404 });
  }
  addAuthInterceptor(_token) {
    this.logger.debug('addAuthInterceptor');
  }
  consentAgreement(agreementId) {
    const userId = this.storage.get(STORAGE_KEY_KIMLIK_USER_ID);
    const user = this.database.kimlikUsers[userId];
    if (!user) {
      this.logger.warnGroup('consentAgreement: user not found', { userId, agreementId });
      return Promise.reject(notFound());
    }
    const agreement = this.database.onayAgreements[agreementId];
    if (!agreement) {
      this.logger.warnGroup('consentAgreement: agreement not found', { userId, agreementId });
      return Promise.reject(notFound());
    }
    const totalConsents = Object.keys(this.database.onayConsents).length;
    const newConsentId = `onayConsents${totalConsents + 1}`;
    const consent = AgreementConsent.decode({
      _id: newConsentId,
      _created: new Date(),
      _updated: new Date(),
      agreement,
      user,
    });
    this.database.onayConsents[newConsentId] = consent;
    return Promise.resolve(consent);
  }
  getAgreement(id) {
    return Promise.resolve(this.database.onayAgreements[id]);
  }
  activateMembership(membershipConfigId, membershipId) {
    const membershipConfig = this.database.uyeMembershipConfigs[membershipConfigId];
    if (!membershipConfig) {
      this.logger.warnGroup('getMembership: config not found', { membershipConfigId, membershipId });
      return Promise.reject(`UyeApiDemo.getMembership: Membership config "${membershipConfigId}" not found`);
    }
    const membershipsTable = this.database[membershipConfig.name];
    if (!membershipsTable) {
      this.logger.warnGroup('getMembership: table not found', { membershipConfigId, membershipId });
      return Promise.reject(`UyeApiDemo.getMembership: Memberships table "${membershipsTable}" not found`);
    }
    const keys = Object.keys(membershipsTable);
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i];
      if (membershipsTable[key]._id === membershipId) {
        this.logger.debugGroup('activateMembership', {
          membership: membershipsTable[key],
          membershipConfigId,
          membershipId,
        });
        membershipsTable[key].status = 'active';
        return Promise.resolve(membershipsTable[key]);
      }
    }
    this.logger.warnGroup('getMembership: membership not found', { membershipConfigId, membershipId });
    return Promise.reject(notFound());
  }
  getMembership(membershipConfigId, membershipId) {
    this.logger.debug('getMembership');
    const membershipConfig = this.database.uyeMembershipConfigs[membershipConfigId];
    if (!membershipConfig) {
      this.logger.warnGroup('getMembership: config not found', { membershipConfigId, membershipId });
      return Promise.reject(`UyeApiDemo.getMembership: Membership config "${membershipConfigId}" not found`);
    }
    const membershipsTable = this.database[membershipConfig.name];
    if (!membershipsTable) {
      this.logger.warnGroup('getMembership: table not found', { membershipConfigId, membershipId });
      return Promise.reject(`UyeApiDemo.getMembership: Memberships table "${membershipsTable}" not found`);
    }
    const keys = Object.keys(membershipsTable);
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i];
      if (membershipsTable[key]._id === membershipId) {
        this.logger.debugGroup('getMembership', {
          membership: membershipsTable[key],
          membershipConfigId,
          membershipId,
        });
        return Promise.resolve(Membership.decode(membershipsTable[key]));
      }
    }
    this.logger.warnGroup('getMembership: membership not found', { membershipConfigId, membershipId });
    return Promise.reject(notFound());
  }
  getMembershipsOfUser(userId) {
    this.logger.debugGroup('getMembershipsOfUser', { userId });
    const ms = [];
    for (let membershipConfigId in this.database.uyeMembershipConfigs) {
      const membershipsTable = this.database[this.database.uyeMembershipConfigs[membershipConfigId].name];
      if (!membershipsTable) {
        return Promise.reject(`UyeApiDemo.getMembership: Memberships table "${membershipsTable}" not found`);
      }
      for (let membershipId in membershipsTable) {
        if (membershipsTable[membershipId].user._id === userId) {
          ms.push(membershipsTable[membershipId]);
        }
      }
    }
    return Promise.resolve({ results: ms });
  }
  getMembershipConfig(membershipConfigId) {
    const membershipConfig = this.database[membershipConfigId];
    if (!membershipConfig) {
      return Promise.reject(`UyeApiDemo.getMembership: Membership config "${membershipConfigId}" not found`);
    }
    return Promise.resolve(membershipConfig);
  }
  getMembershipConfigWithName(name) {
    const membershipConfigIds = Object.keys(this.database.uyeMembershipConfigs);
    for (let i = 0; i < membershipConfigIds.length; i++) {
      const membershipConfigId = membershipConfigIds[i];
      const membershipConfig = this.database.uyeMembershipConfigs[membershipConfigId];
      if (membershipConfig.name === name) {
        this.logger.debugGroup('getMembershipConfigWithName', { name, membershipConfig });
        return Promise.resolve(membershipConfig);
      }
    }
    this.logger.errorGroup('getMembershipConfigWithName: membership not found', { name });
    return Promise.reject(notFound());
  }
  updateMembership(membershipConfigId, membershipId, data) {
    this.logger.debug('updateMembership');
    const membershipConfig = this.database.uyeMembershipConfigs[membershipConfigId];
    if (!membershipConfig) {
      this.logger.warnGroup('updateMembership: config not found', { membershipConfigId, membershipId });
      return Promise.reject(notFound());
    }
    const membershipsTable = this.database[membershipConfig.name];
    if (!membershipsTable) {
      this.logger.warnGroup('updateMembership: table not found', { membershipConfigId, membershipId });
      return Promise.reject(notFound());
    }
    const keys = Object.keys(membershipsTable);
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i];
      if (membershipsTable[key]._id === membershipId) {
        const membership = membershipsTable[key];
        this.logger.debugGroup('updateMembership', {
          membership,
          membershipConfigId,
          membershipId,
        });
        membershipsTable[key] = Membership.decode(Object.assign(Object.assign({}, membership), data));
        return Promise.resolve(membershipsTable[key]);
      }
    }
    this.logger.warnGroup('getMembership: membership not found', { membershipConfigId, membershipId });
    return Promise.reject(notFound());
  }
}

export { AgreementConsent as A, DataApiDemo as D, InstanceStorage as I, KimlikApiDemo as K, TakvimApiDemo as T, UyeApiDemo as U, AtamaApiDemo as a };
