'use strict';

const apiBase = require('./apiBase-e4ebaf8b.js');
const FieldModelGenerator = require('./FieldModelGenerator-1900d81a.js');
require('./index-e751cab0.js');
const index$3 = require('./index-0783d14f.js');
const index$1 = require('./index-e8e4d80b.js');
const referenceField = require('./reference-field-1239b0c3.js');
const index$2 = require('./index-9d3d3d15.js');
const index = require('./index-61f9621a.js');
const dataModel = require('./data-model-9afb7f54.js');
const membership = require('./membership-ed8d3277.js');
const User = require('./User-e889279b.js');
const CalendarConfig = require('./CalendarConfig-ee7bb722.js');
const attachment = require('./attachment-b0acc4c1.js');

const skills = [
  'academic',
  'accounting',
  'activism',
  'ads',
  'advertising',
  'affiliate-marketing',
  'analytics',
  'apis',
  'ar',
  'art',
  'artificial-intelligence',
  'audit',
  'automotive',
  'b2b',
  'b2c',
  'backend',
  'banking',
  'behavior-change',
  'bidding',
  'big-data',
  'biodiversity',
  'biotechnology',
  'blockchain',
  'blogs',
  'branching',
  'brand',
  'broadcasting',
  'buildings',
  'business',
  'business-administration',
  'business-dev',
  'business-model',
  'business-planning',
  'c2c',
  'chemistry',
  'churn-management',
  'circular-economy',
  'cloud-computing',
  'coding',
  'communications',
  'communities',
  'community-management',
  'construction',
  'content-management',
  'content-marketing',
  'contract-administration',
  'crowdfunding',
  'crowd-sourcing',
  'cryptocurrency',
  'customer-relations',
  'customs',
  'data-science',
  'deep-learning',
  'defense-industry',
  'delivery-services',
  'demodays',
  'design',
  'design-thinking',
  'diabetes',
  'diagnostics',
  'digital-marketing',
  'distribution',
  'drip-marketing',
  'drones',
  'dropshipping',
  'earth-observation',
  'e-commerce',
  'edtech',
  'education',
  'e-learning',
  'electric-cars',
  'elevator-pitch',
  'email-marketing',
  'emea',
  'employee-engagement',
  'energy',
  'entrepreneurship',
  'esports',
  'estate',
  'eu',
  'event-management',
  'executive-coaching',
  'finance',
  'fintech',
  'fmcg',
  'food',
  'foreign-trade',
  'franchising',
  'frontend',
  'funding',
  'fundraising-strategy',
  'game-development',
  'gdpr',
  'gov-relations',
  'grants',
  'graphic-design',
  'growth-hacking',
  'hardware',
  'health',
  'human-resources',
  'ico',
  'idea-proof',
  'indiegogo',
  'innovation',
  'insurance',
  'insuretech',
  'international-sales',
  'investor-relations',
  'iot',
  'ipo',
  'it',
  'kickstarter',
  'landing-pages',
  'law',
  'leadership',
  'lead-generation',
  'lean-startup',
  'life-sciences',
  'machine-learning',
  'management-consulting',
  'marketing',
  'marketing-automations',
  'marketplace',
  'market-research',
  'materials',
  'materials-science',
  'medicine',
  'medtech',
  'mena',
  'mindfulness',
  'mobile-development',
  'motivation',
  'nanotechnology',
  'networking',
  'nutrition',
  'online-games',
  'open-source',
  'organic-foods',
  'organizational-development',
  'patent',
  'payment-systems',
  'pitch-decks',
  'pitching',
  'planning',
  'politics',
  'presentation-design',
  'presentation-skills',
  'press',
  'pricing',
  'privacy',
  'procurement',
  'prod',
  'prod-dev',
  'professional-coaching',
  'project-management',
  'psychology',
  'public-relations',
  'publishing',
  'purchasing',
  'quality',
  'recruitment',
  'renewables',
  'reseller-management',
  'resilience',
  'robotics',
  'saas',
  'sales',
  'satellite-navigation',
  'search-engines',
  'sea-technologies',
  'security',
  'sem',
  'service-design',
  'sharing-economy',
  'shipping',
  'silicon-valley',
  'smart-cities',
  'social-entrepreneurship',
  'social-media',
  'soft-skills',
  'software',
  'software-dev',
  'solar-power',
  'space-tech',
  'sports',
  'statistics',
  'storytelling',
  'strategy',
  'supply-chain',
  'sustainability',
  'talent-management',
  'taxes',
  'team-management',
  'tech',
  'telecom',
  'time-management',
  'tourism',
  'transport',
  'travel',
  'ui',
  'unit-economics',
  'ux',
  'ux-design',
  'ux-research',
  'vc',
  'vegan-foods',
  'viral-marketing',
  'virology',
  'vr',
  'waste',
  'water',
  'wind-power',
  'youtube',
];

const skillsEN = {
  analytics: 'Analytics',
  business: 'Business',
  chemistry: 'Chemistry',
  'data-science': 'Data Science',
  'design-thinking': 'Design Thinking',
  diabetes: 'Diabetes',
  diagnostics: 'Diagnostics',
  'graphic-design': 'Graphic Design',
  'life-sciences': 'Life sciences',
  medicine: 'Medicine',
  medtech: 'Medtech',
  pitching: 'Pitching',
  'presentation-design': 'Presentation Design',
  'service-design': 'Service Design',
  'ux-design': 'UX design',
  'ux-research': 'UX research',
  virology: 'Virology',
  academic: 'Academic',
  accounting: 'Accounting',
  activism: 'Activism',
  ads: 'Ads',
  advertising: 'Advertising',
  'affiliate-marketing': 'Affiliate Marketing',
  apis: 'APIs',
  ar: 'AR Augmented Reality',
  art: 'Art',
  'artificial-intelligence': 'Ai Artificial Intelligence',
  audit: 'Audit',
  automotive: 'Automotive',
  b2b: 'B2B',
  b2c: 'B2C',
  backend: 'Backend',
  banking: 'Banking',
  'behavior-change': 'Behavior Change',
  bidding: 'Bidding',
  'big-data': 'Big Data',
  biodiversity: 'Biodiversity',
  biotechnology: 'Biotechnology',
  blockchain: 'Blockchain',
  blogs: 'Blogs',
  branching: 'Branching',
  brand: 'Brand',
  broadcasting: 'Broadcasting',
  buildings: 'Buildings',
  'business-administration': 'Business Administration',
  'business-dev': 'Business Development',
  'business-model': 'Business Model',
  'business-planning': 'Business Planning',
  c2c: 'C2C',
  'churn-management': 'Churn Management',
  'circular-economy': 'Circular Economy',
  'cloud-computing': 'Cloud Computing',
  coding: 'Coding',
  communications: 'Communications',
  communities: 'Communities',
  'community-management': 'Community Management',
  construction: 'Construction',
  'content-management': 'Content Management',
  'content-marketing': 'Content Marketing',
  'contract-administration': 'Contract Administration',
  crowdfunding: 'CrowdFunding',
  'crowd-sourcing': 'Crowd Sourcing',
  cryptocurrency: 'CryptoCurrency',
  'customer-relations': 'Customer Relations',
  customs: 'Customs',
  'deep-learning': 'Deep Learning',
  'defense-industry': 'Defense Industry',
  'delivery-services': 'Delivery Services',
  demodays: 'Demodays',
  design: 'Design',
  'digital-marketing': 'Digital Marketing',
  distribution: 'Distribution',
  'drip-marketing': 'Drip Marketing',
  drones: 'Drones',
  dropshipping: 'Dropshipping',
  'earth-observation': 'Earth Observation',
  'e-commerce': 'E-Commerce',
  edtech: 'EdTech',
  education: 'Education',
  'e-learning': 'E-Learning',
  'electric-cars': 'Electric Cars',
  'elevator-pitch': 'Elevator Pitch',
  'email-marketing': 'Email Marketing',
  emea: 'EMEA Region',
  'employee-engagement': 'Employee Engagement',
  energy: 'Energy',
  entrepreneurship: 'Entrepreneurship',
  esports: 'ESports',
  estate: 'Estate',
  eu: 'EU European Union',
  'event-management': 'Event Management',
  'executive-coaching': 'Executive Coaching',
  finance: 'Finance',
  fintech: 'FinTech',
  fmcg: 'FMCG',
  food: 'Food',
  'foreign-trade': 'Foreign Trade',
  franchising: 'Franchising',
  frontend: 'Frontend',
  funding: 'Funding',
  'fundraising-strategy': 'Fundraising Strategy',
  'game-development': 'Game Development',
  gdpr: 'GDPR',
  'gov-relations': 'Government Relations',
  grants: 'Grants',
  'growth-hacking': 'Growth Hacking',
  hardware: 'Hardware',
  health: 'Health',
  'human-resources': 'HR Human Resources',
  ico: 'ICO',
  'idea-proof': 'Idea Proof',
  indiegogo: 'Indiegogo',
  innovation: 'Innovation',
  insurance: 'Insurance',
  insuretech: 'InsureTech',
  'international-sales': 'International Sales',
  'investor-relations': 'Investor Relations',
  iot: 'IoT',
  ipo: 'IPO',
  it: 'IT',
  kickstarter: 'Kickstarter',
  'landing-pages': 'Landing Pages',
  law: 'Law',
  leadership: 'Leadership',
  'lead-generation': 'Lead Generation',
  'lean-startup': 'Lean Startup',
  'machine-learning': 'Machine Learning',
  'management-consulting': 'Management Consulting',
  marketing: 'Marketing',
  'marketing-automations': 'Marketing Automations',
  marketplace: 'Marketplace',
  'market-research': 'Market Research',
  materials: 'Materials',
  'materials-science': 'Materials Science',
  mena: 'MENA Region',
  mindfulness: 'Mindfulness',
  'mobile-development': 'Mobile Development',
  motivation: 'Motivation',
  nanotechnology: 'Nanotechnology',
  networking: 'Networking',
  nutrition: 'Nutrition',
  'online-games': 'Online Games',
  'open-source': 'Open Source',
  'organic-foods': 'Organic Foods',
  'organizational-development': 'Organizational Development',
  patent: 'Patent',
  'payment-systems': 'Payment Systems',
  'pitch-decks': 'Pitch Decks',
  planning: 'Planning',
  politics: 'Politics',
  'presentation-skills': 'Presentation Skills',
  press: 'Press',
  pricing: 'Pricing',
  privacy: 'Privacy',
  procurement: 'Procurement',
  prod: 'Product',
  'prod-dev': 'Product Development',
  'professional-coaching': 'Professional Coaching',
  'project-management': 'Project Management',
  psychology: 'Psychology',
  'public-relations': 'PR Public Relations',
  publishing: 'Publishing',
  purchasing: 'Purchasing ',
  quality: 'Quality',
  recruitment: 'Recruitment',
  renewables: 'Renewables',
  'reseller-management': 'Reseller Management',
  resilience: 'Resilience',
  robotics: 'Robotics',
  saas: 'SaaS',
  sales: 'Sales',
  'satellite-navigation': 'Satellite Navigation',
  'search-engines': 'Search Engines',
  'sea-technologies': 'Sea Technologies',
  security: 'Security',
  sem: 'SEM Serch Engine Marketing',
  'sharing-economy': 'Sharing Economy',
  shipping: 'Shipping',
  'silicon-valley': 'Silicon Valley',
  'smart-cities': 'Smart Cities',
  'social-entrepreneurship': 'Social Entrepreneurship',
  'social-media': 'Social media',
  'soft-skills': 'Soft Skills',
  software: 'Software',
  'software-dev': 'Software Development',
  'solar-power': 'Solar Power',
  'space-tech': 'Space Tech',
  sports: 'Sports',
  statistics: 'Statistics',
  storytelling: 'Storytelling',
  strategy: 'Strategy',
  'supply-chain': 'Supply Chain',
  sustainability: 'Sustainability',
  'talent-management': 'Talent Management',
  taxes: 'Taxes',
  'team-management': 'Team Management',
  tech: 'Tech',
  telecom: 'Telecom',
  'time-management': 'Time Management',
  tourism: 'Tourism',
  transport: 'Transport',
  travel: 'Travel',
  ui: 'UI',
  'unit-economics': 'Unit Economics',
  ux: 'UX',
  vc: 'VC Venture Capitals',
  'vegan-foods': 'Vegan foods',
  'viral-marketing': 'Viral Marketing',
  vr: 'VR Virtual Reality',
  waste: 'Waste',
  water: 'Water',
  'wind-power': 'Wind Power',
  youtube: 'Youtube',
};

const skillsPtBr = {
  analytics: 'Analytics',
  business: 'Business',
  chemistry: 'Chemistry',
  'data-science': 'Data Science',
  'design-thinking': 'Design Thinking',
  diabetes: 'Diabetes',
  diagnostics: 'Diagnostics',
  'graphic-design': 'Graphic Design',
  'life-sciences': 'Life sciences',
  medicine: 'Medicine',
  medtech: 'Medtech',
  pitching: 'Pitching',
  'presentation-design': 'Presentation Design',
  'service-design': 'Service Design',
  'ux-design': 'UX design',
  'ux-research': 'UX research',
  virology: 'Virology',
  academic: 'Academic',
  accounting: 'Accounting',
  activism: 'Activism',
  ads: 'Ads',
  advertising: 'Advertising',
  'affiliate-marketing': 'Affiliate Marketing',
  apis: 'APIs',
  ar: 'AR Augmented Reality',
  art: 'Art',
  'artificial-intelligence': 'Ai Artificial Intelligence',
  audit: 'Audit',
  automotive: 'Automotive',
  b2b: 'B2B',
  b2c: 'B2C',
  backend: 'Backend',
  banking: 'Banking',
  'behavior-change': 'Behavior Change',
  bidding: 'Bidding',
  'big-data': 'Big Data',
  biodiversity: 'Biodiversity',
  biotechnology: 'Biotechnology',
  blockchain: 'Blockchain',
  blogs: 'Blogs',
  branching: 'Branching',
  brand: 'Brand',
  broadcasting: 'Broadcasting',
  buildings: 'Buildings',
  'business-administration': 'Business Administration',
  'business-dev': 'Business Development',
  'business-model': 'Business Model',
  'business-planning': 'Business Planning',
  c2c: 'C2C',
  'churn-management': 'Churn Management',
  'circular-economy': 'Circular Economy',
  'cloud-computing': 'Cloud Computing',
  coding: 'Coding',
  communications: 'Communications',
  communities: 'Communities',
  'community-management': 'Community Management',
  construction: 'Construction',
  'content-management': 'Content Management',
  'content-marketing': 'Content Marketing',
  'contract-administration': 'Contract Administration',
  crowdfunding: 'CrowdFunding',
  'crowd-sourcing': 'Crowd Sourcing',
  cryptocurrency: 'CryptoCurrency',
  'customer-relations': 'Customer Relations',
  customs: 'Customs',
  'deep-learning': 'Deep Learning',
  'defense-industry': 'Defense Industry',
  'delivery-services': 'Delivery Services',
  demodays: 'Demodays',
  design: 'Design',
  'digital-marketing': 'Digital Marketing',
  distribution: 'Distribution',
  'drip-marketing': 'Drip Marketing',
  drones: 'Drones',
  dropshipping: 'Dropshipping',
  'earth-observation': 'Earth Observation',
  'e-commerce': 'E-Commerce',
  edtech: 'EdTech',
  education: 'Education',
  'e-learning': 'E-Learning',
  'electric-cars': 'Electric Cars',
  'elevator-pitch': 'Elevator Pitch',
  'email-marketing': 'Email Marketing',
  emea: 'EMEA Region',
  'employee-engagement': 'Employee Engagement',
  energy: 'Energy',
  entrepreneurship: 'Entrepreneurship',
  esports: 'ESports',
  estate: 'Estate',
  eu: 'EU European Union',
  'event-management': 'Event Management',
  'executive-coaching': 'Executive Coaching',
  finance: 'Finance',
  fintech: 'FinTech',
  fmcg: 'FMCG',
  food: 'Food',
  'foreign-trade': 'Foreign Trade',
  franchising: 'Franchising',
  frontend: 'Frontend',
  funding: 'Funding',
  'fundraising-strategy': 'Fundraising Strategy',
  'game-development': 'Game Development',
  gdpr: 'GDPR',
  'gov-relations': 'Government Relations',
  grants: 'Grants',
  'growth-hacking': 'Growth Hacking',
  hardware: 'Hardware',
  health: 'Health',
  'human-resources': 'HR Human Resources',
  ico: 'ICO',
  'idea-proof': 'Idea Proof',
  indiegogo: 'Indiegogo',
  innovation: 'Innovation',
  insurance: 'Insurance',
  insuretech: 'InsureTech',
  'international-sales': 'International Sales',
  'investor-relations': 'Investor Relations',
  iot: 'IoT',
  ipo: 'IPO',
  it: 'IT',
  kickstarter: 'Kickstarter',
  'landing-pages': 'Landing Pages',
  law: 'Law',
  leadership: 'Leadership',
  'lead-generation': 'Lead Generation',
  'lean-startup': 'Lean Startup',
  'machine-learning': 'Machine Learning',
  'management-consulting': 'Management Consulting',
  marketing: 'Marketing',
  'marketing-automations': 'Marketing Automations',
  marketplace: 'Marketplace',
  'market-research': 'Market Research',
  materials: 'Materials',
  'materials-science': 'Materials Science',
  mena: 'MENA Region',
  mindfulness: 'Mindfulness',
  'mobile-development': 'Mobile Development',
  motivation: 'Motivation',
  nanotechnology: 'Nanotechnology',
  networking: 'Networking',
  nutrition: 'Nutrition',
  'online-games': 'Online Games',
  'open-source': 'Open Source',
  'organic-foods': 'Organic Foods',
  'organizational-development': 'Organizational Development',
  patent: 'Patent',
  'payment-systems': 'Payment Systems',
  'pitch-decks': 'Pitch Decks',
  planning: 'Planning',
  politics: 'Politics',
  'presentation-skills': 'Presentation Skills',
  press: 'Press',
  pricing: 'Pricing',
  privacy: 'Privacy',
  procurement: 'Procurement',
  prod: 'Product',
  'prod-dev': 'Product Development',
  'professional-coaching': 'Professional Coaching',
  'project-management': 'Project Management',
  psychology: 'Psychology',
  'public-relations': 'PR Public Relations',
  publishing: 'Publishing',
  purchasing: 'Purchasing ',
  quality: 'Quality',
  recruitment: 'Recruitment',
  renewables: 'Renewables',
  'reseller-management': 'Reseller Management',
  resilience: 'Resilience',
  robotics: 'Robotics',
  saas: 'SaaS',
  sales: 'Sales',
  'satellite-navigation': 'Satellite Navigation',
  'search-engines': 'Search Engines',
  'sea-technologies': 'Sea Technologies',
  security: 'Security',
  sem: 'SEM Serch Engine Marketing',
  'sharing-economy': 'Sharing Economy',
  shipping: 'Shipping',
  'silicon-valley': 'Silicon Valley',
  'smart-cities': 'Smart Cities',
  'social-entrepreneurship': 'Social Entrepreneurship',
  'social-media': 'Social media',
  'soft-skills': 'Soft Skills',
  software: 'Software',
  'software-dev': 'Software Development',
  'solar-power': 'Solar Power',
  'space-tech': 'Space Tech',
  sports: 'Sports',
  statistics: 'Statistics',
  storytelling: 'Storytelling',
  strategy: 'Strategy',
  'supply-chain': 'Supply Chain',
  sustainability: 'Sustainability',
  'talent-management': 'Talent Management',
  taxes: 'Taxes',
  'team-management': 'Team Management',
  tech: 'Tech',
  telecom: 'Telecom',
  'time-management': 'Time Management',
  tourism: 'Tourism',
  transport: 'Transport',
  travel: 'Travel',
  ui: 'UI',
  'unit-economics': 'Unit Economics',
  ux: 'UX',
  vc: 'VC Venture Capitals',
  'vegan-foods': 'Vegan foods',
  'viral-marketing': 'Viral Marketing',
  vr: 'VR Virtual Reality',
  waste: 'Waste',
  water: 'Water',
  'wind-power': 'Wind Power',
  youtube: 'Youtube',
};

const skillsTr = {
  'business-model': 'İş Modeli',
  'lean-startup': 'Yalın Girişim',
  'business-dev': 'İş Geliştirme',
  'business-administration': 'İş Yönetimi',
  'market-research': 'Pazar Araştırması',
  pricing: 'Fiyatlandırma',
  statistics: 'İstatistik',
  'idea-proof': 'Fikir Doğrulama',
  leadership: 'Liderlik',
  entrepreneurship: 'Girişimcilik',
  'management-consulting': 'Yönetim Danışmanlığı',
  strategy: 'Strateji',
  'project-management': 'Proje Yönetimi',
  planning: 'Planlama',
  'human-resources': 'İnsan Kaynakları HR',
  law: 'Hukuk',
  finance: 'Finans',
  accounting: 'Muhasebe',
  audit: 'Denetim',
  brand: 'Marka',
  patent: 'Patent',
  'foreign-trade': 'Dış Ticaret',
  customs: 'Gümrük',
  sales: 'Satış',
  marketing: 'Pazarlama',
  ads: 'Reklam',
  'digital-marketing': 'Dijital Pazarlama',
  'growth-hacking': 'Kullanıcı Edinme',
  'search-engines': 'Arama Motorları',
  'social-media': 'Sosyal Medya',
  'content-management': 'İçerik Yönetimi',
  'public-relations': 'PR Halkla İlişkiler',
  'customer-relations': 'Müşteri İlişkileri',
  'gov-relations': 'Devlet İle İlişkiler',
  funding: 'Fon Bulma',
  'investor-relations': 'Yatırımcı İlişkileri',
  'crowd-sourcing': 'Kitlesel Fonlama',
  grants: 'Hibe ve Destekler',
  b2b: 'B2B',
  b2c: 'B2C',
  c2c: 'C2C',
  design: 'Tasarım',
  ux: 'UX',
  ui: 'UI',
  'software-dev': 'Yazılım Geliştirme',
  'prod-dev': 'Ürün Geliştirme',
  quality: 'Kalite Yönetimi',
  prod: 'Üretim',
  distribution: 'Dağıtım',
  tech: 'Teknoloji',
  it: 'IT',
  software: 'Yazılım',
  hardware: 'Donanım',
  iot: 'IoT',
  telecom: 'Telekom',
  'cloud-computing': 'Bulut Bilişim',
  saas: 'SaaS',
  'big-data': 'Big Data',
  banking: 'Bankacılık',
  fintech: 'FinTech',
  'e-commerce': 'E-ticaret',
  marketplace: 'Pazaryeri',
  education: 'Eğitim',
  health: 'Sağlık',
  nutrition: 'Gıda',
  tourism: 'Turizm',
  construction: 'İnşaat',
  estate: 'Emlak',
  automotive: 'Otomotiv',
  art: 'Sanat',
  sports: 'Spor',
  press: 'Basın',
  publishing: 'Yayıncılık',
  advertising: 'Reklamcılık',
  energy: 'Enerji',
  sustainability: 'Sürdürülebilirlik',
  resilience: 'Dayanıklılık',
  procurement: 'Tedarik',
  renewables: 'Yenilenebilir Enerji',
  buildings: 'Yapılar',
  'electric-cars': 'Electirikli Araçlar',
  'circular-economy': 'Döngüsel Ekonomi',
  'supply-chain': 'Tedarik Zinciri',
  'behavior-change': 'Davranış Değişimi',
};

var __rest = (undefined && undefined.__rest) || function (s, e) {
  var t = {};
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
    t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
      if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
        t[p[i]] = s[p[i]];
    }
  return t;
};
function getRequestStatus(request) {
  if (request.status === 'completed') {
    return 'completed';
  }
  if (request.rejectedAt) {
    return 'rejected';
  }
  else if (request.canceledAt) {
    return 'canceled';
  }
  else if (request.acceptedAt) {
    return 'accepted';
  }
  else if (request.requestedAt) {
    return 'requested';
  }
}
const embeddedTranslations = {
  en: {
    title: 'Title',
    bio: 'Bio',
    skills: 'Professional Expertise',
    search: 'Search',
    goToProfilePage: 'Go to Profile Page',
    info: 'Info',
    getMeeting: 'Get Meeting',
    viewDetails: 'View Details',
    meetings: 'Meetings',
    follow: 'Follow',
    unfollow: 'Unfollow',
    sendMessage: 'Send Message'
  },
  'pt-br': {
    title: 'Titulo',
    bio: 'Bio',
    skills: 'Expertise profissional',
    search: 'Buscar',
    goToProfilePage: 'Vá para a página do perfil',
    info: 'Informação',
    getMeeting: 'Agendar Sessões',
    viewDetails: 'Ver detalhes',
    meetings: 'Sessões',
    follow: 'Seguir',
    unfollow: 'Deixar de seguir',
    sendMessage: 'Enviar mensagem'
  },
  tr: {
    title: 'Ünvan',
    bio: 'Özgeçmiş',
    skills: 'Uzmanlık alanları',
    search: 'Ara',
    goToProfilePage: 'Profil Sayfasına Git',
    info: 'Bilgi',
    getMeeting: 'Toplantı Oluştur',
    viewDetails: 'Detayları Gör',
    meetings: 'Toplantılar',
    follow: 'Takip Et',
    unfollow: 'Takibi Bırak',
    sendMessage: 'Mesaj Gönder'
  },
};
function getEmbeddedTranslation(language, key) {
  return (embeddedTranslations[language] || embeddedTranslations.en)[key];
}
const legacyProfileFields = (language = 'en') => {
  const strings = embeddedTranslations[language] || embeddedTranslations.en;
  let skillStrings = skillsEN;
  switch (language) {
    case 'pt-br':
      skillStrings = skillsPtBr;
      break;
    case 'tr':
      skillStrings = skillsTr;
      break;
  }
  return [
    FieldModelGenerator.generateFieldModelFromRawData({ id: 'title', title: strings.title, type: 'text' }),
    FieldModelGenerator.generateFieldModelFromRawData({ id: 'bio', title: strings.bio, type: 'text', lines: 3 }),
    FieldModelGenerator.generateFieldModelFromRawData({
      id: 'skills',
      title: strings.skills,
      type: 'multiple-choice',
      inputType: 'tag-cloud',
      options: skills.map(skill => ({
        label: skillStrings[skill] || skill, value: skill,
      })),
    }),
  ];
};
const commonUserInfoFields = [
  FieldModelGenerator.generateFieldModelFromRawData({ id: 'name', type: 'text' }),
  FieldModelGenerator.generateFieldModelFromRawData({ id: 'imageUrl', type: 'image' }),
  FieldModelGenerator.generateFieldModelFromRawData({ id: 'title', title: 'Title', type: 'text' }),
  FieldModelGenerator.generateFieldModelFromRawData({ id: 'bio', title: 'Bio', type: 'text', lines: 3 }),
  FieldModelGenerator.generateFieldModelFromRawData({ id: 'imagePlaceholderValue', title: '', type: 'text' }),
  FieldModelGenerator.generateFieldModelFromRawData({
    id: 'skills',
    title: 'Professional Expertise',
    type: 'multiple-choice',
    inputType: 'tag-cloud',
    options: skills.map(skill => ({
      label: skillsEN[skill], value: skill,
    })),
  }),
];
const groupInfoFields = [
  FieldModelGenerator.generateFieldModelFromRawData({ id: 'imageUrl', type: 'image' }),
  FieldModelGenerator.generateFieldModelFromRawData({ id: 'title', title: 'Title', type: 'text' }),
  FieldModelGenerator.generateFieldModelFromRawData({ id: 'description', title: 'Description', type: 'text', lines: 3 }),
  FieldModelGenerator.generateFieldModelFromRawData({ id: 'imagePlaceholderValue', title: '', type: 'text' }),
  new referenceField.ReferenceField('members', 'Members', 'name', 'imageUrl', 'users', [
    new attachment.AttachmentField('imageUrl', ''),
    new index.TextField('firstName', 'First Name'),
    new index.TextField('lastName', 'Last Name'),
    new index.TextField('name', 'Name'),
  ], false),
];
function getQueryParamValueFromNestedFilter(filter) {
  if (!filter) {
    return {};
  }
  if (filter === null || filter === void 0 ? void 0 : filter.filters) {
    let nestedValues = {};
    filter.filters.forEach(f => {
      nestedValues = Object.assign(nestedValues, getQueryParamValueFromNestedFilter(f));
    });
    return nestedValues;
  }
  if (!filter.id) {
    return {};
  }
  return {
    [filter.id]: filter.value,
  };
}
function convertDevingenQueryToMemberListQuery(query) {
  // console.log(JSON.stringify(query.filter, null, 2));
  const { limit = 25, skip = 0 } = query;
  const mentornityMemberListQuery = {
    limit, skip,
  };
  const filterValuesFromUI = getQueryParamValueFromNestedFilter(query.filter);
  const fieldIds = Object.keys(filterValuesFromUI);
  fieldIds.forEach(fieldId => {
    if (['search', 'title', 'bio', 'skills'].includes(fieldId)) {
      mentornityMemberListQuery[fieldId] = filterValuesFromUI[fieldId];
    }
    else {
      mentornityMemberListQuery[`metadata.data.${fieldId}`] = filterValuesFromUI[fieldId];
    }
  });
  // console.log(mentornityMemberListQuery);
  return mentornityMemberListQuery;
}
function convertMentornityFieldToDevingenField(field) {
  let dvnField;
  if (field.type === 'ratingStars') {
    dvnField = new index$1.RangeField(field.id, field.title, field.description, 0.2, 0.2, 1).setInputType('stars');
  }
  else if (field.type === 'singleChoice') {
    dvnField = new index$2.SingleChoiceField(field.id, field.title, field.options, field.description, field.inputType, field.placeholder);
  }
  else if (field.type === 'multipleChoice') {
    dvnField = new index$3.MultipleChoiceField(field.id, field.title, field.options, field.description, field.inputType, field.placeholder);
  }
  else {
    dvnField = FieldModelGenerator.generateFieldModelFromRawData(field);
  }
  if (field.required) {
    dvnField.require();
  }
  return dvnField;
}
function convertDevingenAvailabilityToMentornityAvailability(context, mentorship, availability) {
  return {
    status: 'active',
    // slotCount: state.count,
    endDate: new Date(availability.endDate).getTime() / 1000,
    startDate: new Date(availability.startDate).getTime() / 1000,
    meetingDuration: availability.meetingDuration,
    meetingBreaks: availability.breakDuration,
    location: {
      address: availability.location,
      type: availability.locationType,
    },
    createdBy: {
      _type: 'reference',
      _class: 'users',
      _id: context.userId,
    },
    mentorship: {
      _type: 'reference',
      _class: 'mentorships',
      _id: mentorship._id,
    },
    owner: {
      _type: 'reference',
      _class: 'users',
      _id: availability.user._id,
    },
    organisation: {
      _type: 'reference',
      _class: 'organisations',
      _id: context.organisationId,
    },
    recurrence: availability.recurrence,
  };
}
function convertDevingenEventToMentornityEvent(context, organisationConfig, event) {
  var _a, _b, _c;
  const { organisationId, userId, role } = context;
  let guests = [];
  if (event.guestMetadata) {
    // roles are in the guest metadata
    guests = event.guests.map((guest, i) => {
      const collection = event.guestMetadata[i].membershipConfigId;
      return {
        _id: guest._id,
        _class: collection === 'groups' ? 'groups' : 'users',
        _type: 'reference'
      };
    });
  }
  else if (organisationConfig.menteeType === 'group') {
    // TODO remove this part. all meetings should contain guestMetadata and fall into the previous block
    const currentUserAsGuest = event.guests.find(guest => guest._id === userId);
    const otherGuest = event.guests.find(guest => guest._id !== userId);
    // convert the reference class to groups if the mentee type is group
    if (role === 'mentor') {
      // other user must be groups
      otherGuest._ref = 'groups';
    }
    else {
      // mentee is creating the meeting as the group
      currentUserAsGuest._ref = 'groups';
      currentUserAsGuest._id = context.groupId;
    }
    // first user in the array must be mentor ref
    const guestsOrdered = role === 'mentor' ? [currentUserAsGuest, otherGuest] : [otherGuest, currentUserAsGuest];
    guests = guestsOrdered.map(guest => ({
      _id: guest._id,
      _class: guest._ref === 'kimlik-users' ? 'users' : guest._ref,
      _type: 'reference'
    }));
  }
  const meeting = {
    location: (((_a = event.locations) === null || _a === void 0 ? void 0 : _a[0]) || {}),
    // createdBy: convertDevingenRefToMentornityRef(event.createdBy),
    organisation: {
      _id: organisationId,
      _class: 'organisations',
      _type: 'reference'
    },
    guests,
    type: 'meeting',
    status: 'active',
    startDate: new Date(event.startDate).getTime() / 1000,
    endDate: new Date(event.endDate).getTime() / 1000,
  };
  if ((_b = event.availability) === null || _b === void 0 ? void 0 : _b._id) {
    meeting.availability = {
      _id: (_c = event.availability) === null || _c === void 0 ? void 0 : _c._id,
      _class: 'availabilities',
      _type: 'reference'
    };
  }
  if (event.meetingType) {
    meeting.meetingGoalIdentifier = event.meetingType;
  }
  return meeting;
}
function convertMentornityEventToDevingenEvent(event) {
  return Object.assign(Object.assign({}, event), { startDate: new Date(event.startDate * 1000).toISOString(), endDate: new Date(event.endDate * 1000).toISOString(), guests: event.guests.map(guest => (Object.assign(Object.assign({}, guest), { name: guest.firstName ? `${guest.firstName} ${guest.lastName}` : guest.title, initials: guest.firstName ? `${guest.firstName[0]} ${guest.lastName[0]}` : guest.title[0] }))), guestMetadata: event.guests.map((_, i) => {
      if (i === 0) {
        return {
          membershipConfigId: 'mentors',
        };
      }
      return {
        // membershipConfigId: 'mentees',
        membershipConfigId: 'groups',
      };
    }) });
}
function convertUserListToMembershipList(response, membershipConfigId) {
  var _a;
  // separate metadata and user data. consider title, bio and skills as metadata
  return {
    meta: {
      total: ((_a = response.meta) === null || _a === void 0 ? void 0 : _a.total) || 0,
    },
    results: response.results.map((user) => {
      const { metadata, title, bio, skills, // membership data
      _id, email, firstName, lastName, imageUrl, // profile data
      availabilities, } = user;
      // auto generated values. used in cardViewConfig
      const name = `${user.firstName} ${user.lastName}`;
      const initials = `${user.firstName[0]}${user.lastName[0]}`;
      return membership.Membership.decode(Object.assign(Object.assign({ 
        // user id is used as membership id too
        _id }, ((metadata === null || metadata === void 0 ? void 0 : metadata.data) || {})), { title, bio, skills, 
        // user data
        user: { _id, email, firstName, lastName, imageUrl, name, initials }, 
        // used by mentornity-schedule-meeting-button-on-card in mentor card list
        availabilities, 
        // membership config reference in the membership
        config: { _id: membershipConfigId } }));
    }).sort((a, b) => a.user.name.localeCompare(b.user.name))
  };
}
function convertGroupListToMembershipList(response) {
  var _a;
  // separate metadata and user data. consider title, bio and skills as metadata
  return {
    meta: {
      total: ((_a = response.meta) === null || _a === void 0 ? void 0 : _a.total) || 0,
    },
    results: response.results.map((group) => {
      const { _id, title } = group;
      // auto generated values. used in cardViewConfig
      const name = title;
      const initials = title[0];
      return membership.Membership.decode({
        // user id is used as membership id too
        _id,
        // user data
        user: { _id, name, initials },
      });
    }).sort((a, b) => a.user.name.localeCompare(b.user.name))
  };
}
function generateCalendarConfig(config) {
  const { meetingSettings } = config;
  const canMenteesCreateMeeting = !!meetingSettings.menteesCanCreateMeeting;
  const canMentorsCreateMeeting = !!meetingSettings.mentorsCanCreateMeeting;
  if (config.menteeType === 'group') {
    return CalendarConfig.CalendarConfig.decode({
      _id: 'mentornity-calendar-config',
      guestDefinitions: [{ tableId: 'mentors' }, { tableId: 'groups' }],
      permissions: [
        { membershipConfigId: 'mentors', canPickCustomTime: canMentorsCreateMeeting },
        { membershipConfigId: 'groups', canPickCustomTime: canMenteesCreateMeeting },
        { membershipConfigId: 'admins', canPickCustomTime: true }
      ],
    });
  }
  return CalendarConfig.CalendarConfig.decode({
    _id: 'mentornity-calendar-config',
    guestDefinitions: [{ tableId: 'mentors' }, { tableId: 'mentees' }],
    permissions: [
      { membershipConfigId: 'mentors', canPickCustomTime: canMentorsCreateMeeting },
      { membershipConfigId: 'mentees', canPickCustomTime: canMenteesCreateMeeting },
      { membershipConfigId: 'admins', canPickCustomTime: true }
    ],
  });
}
const membershipConfigMentor = membership.MembershipConfig.decode({ _id: 'mentors', roleName: 'mentor' });
const membershipConfigMentee = membership.MembershipConfig.decode({ _id: 'mentees', roleName: 'mentee' });
const membershipConfigGroup = membership.MembershipConfig.decode({ _id: 'groups', roleName: 'group' });
class MentornityBridgeApi {
  constructor(endpoint, context, headers) {
    this.client = new apiBase.APIBase(endpoint, headers);
    this.context = context;
  }
  addAuthInterceptor(_token) {
    // console.log('MBA.addAuthInterceptor', token);
  }
  // DATA API
  get(collection, id, _query) {
    // console.log('MBA.get', collection, id, _query);
    if (collection === 'data-configs') {
      // this request is for getting the data configuration. return the proper data configuration
      if (id === 'mentors') {
        return Promise.resolve(membershipConfigMentor);
      }
      else if (id === 'mentees') {
        return Promise.resolve(membershipConfigMentee);
      }
      else if (id === 'groups') {
        return Promise.resolve(membershipConfigGroup);
      }
    }
    const { organisationId } = this.context;
    if (collection === 'groups') {
      return new Promise((resolve => {
        this.client.get(`groups/${id}`).then(response => {
          resolve(dataModel.DataModel.decode(Object.assign(Object.assign({ 
            // dvn-app-view-atama-member-pair-detail-view expects 'user' field in the 'membership' object
            user: {
              // id is needed here because the user object is sent to web-client when create meeting is clicked
              _id: response._id,
              firstName: response.title,
              lastName: ' ',
            } }, response), { members: (response.members || []).map(member => (Object.assign(Object.assign({}, member), { name: `${member.firstName} ${member.lastName}` }))) })));
        }).catch(_e => {
          // console.log(e);
        });
      }));
    }
    return new Promise((resolve => {
      this.client.get(`organisations/${organisationId}/${collection}/${id}`).then(response => {
        var _a;
        // separate metadata and user data. consider title, bio and skills as metadata
        const { metadata, title, bio, skills } = response, rest = __rest(response, ["metadata", "title", "bio", "skills"]);
        resolve(dataModel.DataModel.decode(Object.assign(Object.assign({ user: User.User.decode(rest) }, (((_a = response.metadata) === null || _a === void 0 ? void 0 : _a.data) || {})), { title, bio, skills })));
      }).catch(_e => {
        // console.log(e);
      });
    }));
  }
  query(collection, query) {
    var _a, _b, _c, _d, _f, _g, _h;
    const { organisationId } = this.context;
    if (collection === 'groups') {
      const search = (_c = (_b = (_a = query === null || query === void 0 ? void 0 : query.filter) === null || _a === void 0 ? void 0 : _a.filters) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.value;
      return new Promise((resolve => {
        this.client.get(`organisations/${organisationId}/${collection}`, { title: search, limit: 1000 }).then(response => resolve(convertGroupListToMembershipList(response)))
          .catch(e => console.log(e));
      }));
    }
    if (['mentees', 'mentors'].includes(collection)) {
      const menteeId = (_d = query === null || query === void 0 ? void 0 : query.filter) === null || _d === void 0 ? void 0 : _d.value;
      if (menteeId) {
        // this request is called by dvn-app-view-detail-view-card that is opened
        // when mentor clicks on the mentee info inside the received requests list
        // and also on the user detail page wrapper
        return new Promise((resolve => {
          this.client.get(`organisations/${organisationId}/${collection}/${menteeId}`).then(response => {
            var _a;
            // separate metadata and user data. consider title, bio and skills as metadata
            const { metadata, title, bio, skills } = response, rest = __rest(response, ["metadata", "title", "bio", "skills"]);
            resolve({
              results: [
                dataModel.DataModel.decode(Object.assign(Object.assign(Object.assign(Object.assign({ user: Object.assign(Object.assign({}, rest), { initials: `${response.firstName[0]} ${response.lastName[0]}`, name: `${response.firstName} ${response.lastName}` }) }, (((_a = response.metadata) === null || _a === void 0 ? void 0 : _a.data) || {})), { title, bio, skills }), rest), { 
                  // membership config reference in the membership
                  config: { _id: collection } }))
              ]
            });
          }).catch(e => {
            console.log(e);
          });
        }));
      }
      else {
        const search = (_h = (_g = (_f = query === null || query === void 0 ? void 0 : query.filter) === null || _f === void 0 ? void 0 : _f.filters) === null || _g === void 0 ? void 0 : _g[0]) === null || _h === void 0 ? void 0 : _h.value;
        return new Promise((resolve => {
          this.client.get(`organisations/${organisationId}/${collection}`, { search }).then(response => resolve(convertUserListToMembershipList(response, collection)))
            .catch(e => console.log(e));
        }));
      }
    }
    else if (['mentee-card-list', 'mentor-card-list'].includes(collection)) {
      const membershipConfigId = collection === 'mentor-card-list' ? 'mentors' : 'mentees';
      const queryParams = convertDevingenQueryToMemberListQuery(query);
      // this request is called by mentornity-user-card-list-wrapper that is shown
      // for the mentee and mentor list pages
      const { organisationId } = this.context;
      const collectionToQuery = collection === 'mentee-card-list' ? 'mentees' : 'mentors';
      return new Promise((resolve => {
        this.client.get(`organisations/${organisationId}/${collectionToQuery}`, Object.assign({ appendAvailabilities: true, appendSubscription: true, expandMetadatas: true }, queryParams)).then(response => resolve(convertUserListToMembershipList(response, membershipConfigId)))
          .catch(e => console.log(e));
      }));
    }
    return Promise.resolve(undefined);
  }
  update(_collection, _id, _body) {
    return Promise.reject({ status: 418 });
  }
  // ATAMA API
  getPairsOfUser(_base, _collection, userRefFieldId, _userRefFieldValue) {
    // console.log('MBA.getPairsOfUser', base, collection, userRefFieldId, userRefFieldValue);
    const { organisationId } = this.context;
    const { menteeType } = this.organisationConfig;
    // if user reference field is subscribed, then it's a mentor viewing its mentees
    const listToFetch = userRefFieldId === 'subscribed'
      ? (menteeType === 'group' ? 'groups' : 'mentees')
      : 'mentors';
    const itemNameToReturn = userRefFieldId === 'subscribed' ? 'subscriber' : 'subscribed';
    const params = listToFetch === 'groups'
      ? { expandCreatedBy: false }
      : { expandMetadatas: true, appendSubscription: true, };
    return new Promise((resolve => {
      this.client.get(`organisations/${organisationId}/${listToFetch}`, params).then(response => {
        // console.log('response', response);
        setTimeout(() => resolve({
          results: response.results
            // show only the active pairs
            .filter(item => { var _a; return ((_a = item.subscription) === null || _a === void 0 ? void 0 : _a.status) === 'active'; })
            .map(item => {
            var _a;
            return ({
              [itemNameToReturn]: [Object.assign(Object.assign(Object.assign({}, item), (((_a = item.metadata) === null || _a === void 0 ? void 0 : _a.data) || {})), { name: `${item.firstName} ${item.lastName}`, imagePlaceholderValue: listToFetch === 'groups'
                    ? ((item.title && item.title.length > 0) ? item.title[0] : '')
                    : `${item.firstName[0]} ${item.lastName[0]}` })],
              status: item.subscription.status,
            });
          }),
          meta: response.meta,
        }), 100);
      }).catch(_e => {
        // console.log(e);
      });
    }));
  }
  getSelectionList(_base, _collection, _pairConfigId, _userRefFieldId, _memberToViewRefFieldId) {
    // console.log('MBA.getSelectionList', base, collection, pairConfigId, userRefFieldId, memberToViewRefFieldId);
    const { organisationId } = this.context;
    return new Promise(resolve => {
      this.client.get(`organisations/${organisationId}/mentors/selection`).then(response => resolve({
        results: response.results.map(item => {
          var _a;
          return (Object.assign(Object.assign(Object.assign({}, item), (((_a = item.metadata) === null || _a === void 0 ? void 0 : _a.data) || {})), { name: `${item.firstName} ${item.lastName}`, initials: `${item.firstName[0]} ${item.lastName[0]}` }));
        })
      })).catch(_e => {
        // console.log(e);
      });
    });
  }
  getSentRequests(_base, _collection, _userRefFieldValue) {
    // console.log('MBA.getSentRequests', base, collection, userRefFieldValue);
    const { organisationId } = this.context;
    return new Promise((resolve => {
      this.client.get(`organisations/${organisationId}/mentors`, { appendRequestSubscriptions: true, limit: 1000 }).then(response => {
        // console.log('response', response);
        setTimeout(() => resolve({
          results: response.results
            // subscription must contain 'requestedAt' field if this subscription is created via selection request
            .filter(item => { var _a; return !!((_a = item.subscription) === null || _a === void 0 ? void 0 : _a.requestedAt); })
            .map(item => ({
            sentTo: User.User.decode(item),
            status: getRequestStatus(item.subscription),
            requestedAt: item.subscription.requestedAt,
            acceptedAt: item.subscription.acceptedAt,
            rejectedAt: item.subscription.rejectedAt,
            canceledAt: item.subscription.canceledAt,
          })),
          meta: response.meta,
        }), 100);
      }).catch(_e => {
        // console.log(e);
      });
    }));
  }
  getReceivedRequests(_base, _collection) {
    // console.log('MBA.getReceivedRequests', base, collection);
    const { organisationId } = this.context;
    return new Promise((resolve => {
      this.client.get(`organisations/${organisationId}/mentees`, { expandMetadatas: true, limit: 1000 }).then(response => {
        setTimeout(() => resolve({
          results: response.results
            // subscription must contain 'requestedAt' field if this subscription is created via selection request
            .filter(item => { var _a; return !!((_a = item.subscription) === null || _a === void 0 ? void 0 : _a.requestedAt); })
            // show only pending requests
            .sort((a, b) => b.subscription.createdAt - a.subscription.createdAt)
            .map(item => ({
            _id: item.subscription._id,
            sentBy: User.User.decode(item),
            status: getRequestStatus(item.subscription),
            requestedAt: item.subscription.requestedAt,
            acceptedAt: item.subscription.acceptedAt,
            rejectedAt: item.subscription.rejectedAt,
            canceledAt: item.subscription.canceledAt,
          })),
          meta: response.meta,
        }), 100);
      }).catch(_e => {
        // console.log(e);
      });
    }));
  }
  sendPairRequest(_base, _collection, _userRefFieldId, userRefFieldValue, _memberToViewRefFieldId, memberToViewData) {
    var _a, _b;
    // console.log('MBA.endPair', base, collection, pairId);
    const { organisationId } = this.context;
    const subscription = {
      mentorship: { _type: 'reference', _class: 'mentorships', _id: memberToViewData.mentorship._id },
      organisation: { _type: 'reference', _class: 'organisations', _id: organisationId },
      subscribed: { _type: 'reference', _class: 'users', _id: memberToViewData._id },
      subscriber: { _type: 'reference', _class: 'users', _id: userRefFieldValue },
      status: ((_b = (_a = this.organisationConfig) === null || _a === void 0 ? void 0 : _a.subscriptionConfig) === null || _b === void 0 ? void 0 : _b.processStartType) === 'startOnSelection'
        ? 'active'
        : 'requested',
    };
    return this.client.post(`subscriptions`, subscription);
    // return Promise.reject({ status: 409 });
  }
  acceptPairRequest(_base, _collection, requestId) {
    return this.client.post(`subscriptions/${requestId}/accept`, {});
  }
  rejectPairRequest(_base, _collection, requestId) {
    return this.client.post(`subscriptions/${requestId}/reject`, {});
  }
  // getMeetingsOfUser(_base: string, _collection: string, _structureId: string, _userRefFieldValue: string): Promise<GetListResponse<DataModel>> {
  //   // console.log('MBA.getMeetingsOfUser', base, collection, structureId, userRefFieldValue);
  //
  //   // the response contains all the meetings with different users
  //   // here we filter the events based on the user id we're viewing
  //   const userIdToView = new URLSearchParams(window.location.search).get('uid');
  //
  //   return new Promise((async resolve => {
  //     const response = await this.client.get<any>(
  //       `organisations/${this.context.organisationDomain}/meetingsInMeetingGoal`,
  //     );
  //     resolve({
  //       results: response.results.filter(meeting => meeting.guests.some(guest => guest._id === userIdToView))
  //     });
  //   }));
  // }
  endPair(_base, _collection, pairId) {
    // console.log('MBA.endPair', base, collection, pairId);
    return new Promise((async (resolve) => {
      const response = await this.client.post(`subscriptions/${pairId}/complete`, {});
      resolve(response);
    }));
  }
  // UYE API
  getAppConfigOfMembership(_id) {
    // console.log('MBA.getAppConfigOfMembership', id);
    return Promise.reject({ status: 418 });
  }
  consentAgreement(_id) {
    // console.log('MBA.consentAgreement', id);
    return Promise.reject({ status: 418 });
  }
  getAgreement(_id) {
    // console.log('MBA.getAgreement', id);
    return Promise.reject({ status: 418 });
  }
  activateMembership(_membershipConfigId, _membershipId) {
    // console.log('MBA.getMembership', id);
    return Promise.reject({ status: 418 });
  }
  getMembership(_membershipConfigId, _membershipId) {
    // console.log('MBA.getMembership', id);
    return Promise.reject({ status: 418 });
  }
  getMembershipsOfUser(_userId) {
    // console.log('MBA.getMembershipsOfUser', userId);
    return Promise.reject({ status: 418 });
  }
  getMembershipConfig(id) {
    console.log('MBA.getMembershipConfig', id);
    return Promise.reject({ status: 418 });
  }
  getMembershipConfigWithName(name) {
    // console.log('MBA.getMembershipConfigWithName', name);
    const { organisationId } = this.context;
    return new Promise((async (resolve) => {
      this.client.get(`organisations/${organisationId}/config`).then(organisationConfig => {
        this.organisationConfig = organisationConfig;
        let fields = [];
        let roleName = '';
        if (name === 'mentees') {
          roleName = 'mentee';
          fields = [
            ...commonUserInfoFields,
            ...organisationConfig.metadatas.mentee
              .map(convertMentornityFieldToDevingenField),
          ];
        }
        else if (name === 'mentors') {
          roleName = 'mentor';
          fields = [
            ...commonUserInfoFields,
            ...organisationConfig.metadatas.mentor
              .map(convertMentornityFieldToDevingenField),
          ];
        }
        else if (name === 'groups') {
          roleName = 'mentee';
          fields = [
            ...groupInfoFields,
          ];
        }
        resolve(membership.MembershipConfig.decode({
          _id: name,
          roleName,
          fields,
        }));
      }).catch(_e => {
        // console.log(e);
      });
    }));
  }
  updateMembership(_membershipConfigId, _membershipId, _data) {
    // console.log('MBA.updateMembership', id, data);
    return Promise.reject({ status: 418 });
  }
  // getAvailabilities(_availabilityConfigId: string): Promise<GetListResponse<Availability>> {
  //   return Promise.reject({ status: 418 });
  // }
  getAvailabilitiesOfUser(userId) {
    const { organisationId, role } = this.context;
    if (role === 'mentor' && userId !== this.context.userId) {
      // mentor is viewing mentee's calendar. return empty availability list
      return Promise.resolve({ results: [] });
    }
    return new Promise((resolve => {
      this.client.get(`organisations/${organisationId}/mentors/${userId}/availabilities`).then(response => {
        resolve({
          results: response.results
            .map(item => (Object.assign(Object.assign({}, item), { breakDuration: item.meetingBreaks, location: item.location.address, locationType: item.location.type, startDate: new Date(item.startDate * 1000), endDate: new Date(item.endDate * 1000) }))),
        });
      }).catch(e => {
        console.log(e);
      });
    }));
  }
  getCalendarConfig(_id) {
    return Promise.resolve(generateCalendarConfig(this.organisationConfig));
  }
  getMeetingsForCalendar(_calendarConfigId, startDate, endDate) {
    return new Promise((async (resolve) => {
      const response = await this.client.get(`organisations/${this.context.organisationDomain}/meetings`, { startDate, endDate, sort: 'startDate', status: 'active' });
      resolve({
        results: response.results.map(convertMentornityEventToDevingenEvent),
      });
    }));
  }
  getMeetingsOfUser(calendarConfigId, guestIDs) {
    if (calendarConfigId === 'mentornity-calendar-config') {
      return new Promise((async (resolve) => {
        const { groupId, organisationId, userId } = this.context;
        const isFetchingGroupMeetings = !!groupId;
        const idToUse = isFetchingGroupMeetings ? groupId : userId;
        const collectionToUse = isFetchingGroupMeetings ? 'groups' : 'users';
        const response = await this.client.get(`${collectionToUse}/${idToUse}/events`, { organisationId: organisationId, limit: 1000 });
        let results = response.results.filter(meeting => meeting.status === 'active');
        if (guestIDs.length > 1) {
          // TODO this should be done in api
          // user is viewing the meetings with another user
          const userIdToView = guestIDs.filter(id => id !== idToUse)[0];
          results = results.filter(meeting => meeting.guests.some(guest => guest._id === userIdToView));
        }
        results = results.map(convertMentornityEventToDevingenEvent);
        resolve({ results });
      }));
    }
    else if (calendarConfigId === 'mentornity-structured-calendar-config') {
      // getting meetings in a structured program
      // the response contains all the meetings with different users
      // here we filter the events based on the user id we're viewing
      const userIdToView = new URLSearchParams(window.location.search).get('uid');
      return new Promise((async (resolve) => {
        const response = await this.client.get(`organisations/${this.context.organisationDomain}/meetingsInMeetingGoal`, { limit: 1000 });
        resolve({
          results: response.results
            .filter(meeting => meeting.guests.some(guest => guest._id === userIdToView))
            .map(meeting => (Object.assign(Object.assign({}, meeting), { meetingType: meeting.meetingGoalIdentifier, startDate: new Date(meeting.startDate * 1000), endDate: new Date(meeting.endDate * 1000) })))
        });
      }));
    }
    return Promise.reject('unexpected-calendar-config');
  }
  getUnavailabilitiesOfUser(_calendarConfigId, userId, _startTime, _endTime) {
    const { role, userId: userIdInContext, groupId } = this.context;
    const isGroupedProgram = this.organisationConfig.menteeType === 'group';
    const isMentorGettingOwnData = role === 'mentor' && userId === userIdInContext;
    const isMentorGettingAnotherGuestData = role === 'mentor' && userId !== userIdInContext;
    const isMenteeGettingOwnData = role === 'mentee' && userId === userIdInContext;
    const isMenteeGettingAnotherGuestData = role === 'mentee' && userId !== userIdInContext;
    let roleToCheck = 'mentors';
    if (isMentorGettingOwnData || isMenteeGettingAnotherGuestData) {
      roleToCheck = 'mentors';
    }
    else if (isMenteeGettingOwnData || isMentorGettingAnotherGuestData) {
      roleToCheck = isGroupedProgram ? 'groups' : 'mentees';
    }
    let idToCheck = userId;
    if (isMenteeGettingOwnData && isGroupedProgram) {
      // mentee is getting its group unavailabilities
      idToCheck = groupId;
    }
    return new Promise((resolve => {
      this.client.get(`organisations/${this.context.organisationId}/${roleToCheck}/${idToCheck}/unavailabilities`).then(response => {
        resolve({
          results: response.results,
        });
      }).catch(e => {
        console.log(e);
      });
    }));
  }
  createMeeting(meeting) {
    const mentornityEvent = convertDevingenEventToMentornityEvent(this.context, this.organisationConfig, meeting);
    // console.log(meeting);
    // console.log(mentornityEvent);
    // return Promise.resolve({
    //   _id: 'fake',
    //   createdAt: 0,
    //   updatedAt: 0,
    // });
    return new Promise(((resolve, reject) => {
      this.client.post('events', mentornityEvent).then(response => {
        resolve(response);
      }).catch(e => {
        reject(e);
      });
    }));
  }
  createAvailability(availability) {
    const mentornityAvailability = convertDevingenAvailabilityToMentornityAvailability(this.context, this.mentorship, availability);
    // console.log(availability);
    // console.log(mentornityAvailability);
    // return Promise.resolve({
    //   _id: 'fake',
    //   createdAt: 0,
    //   updatedAt: 0,
    // });
    return new Promise(((resolve, reject) => {
      this.client.post('availabilities', mentornityAvailability).then(response => {
        resolve(response);
      }).catch(e => {
        reject(e);
      });
    }));
  }
  updateAvailability(availability) {
    const mentornityAvailability = convertDevingenAvailabilityToMentornityAvailability(this.context, this.mentorship, availability);
    // console.log(availability);
    // console.log(mentornityAvailability);
    // return Promise.resolve({
    //   _id: 'fake',
    //   createdAt: 0,
    //   updatedAt: 0,
    // });
    return new Promise(((resolve, reject) => {
      this.client.put(`availabilities/${availability._id}`, mentornityAvailability).then(response => {
        resolve(response);
      }).catch(e => {
        reject(e);
      });
    }));
  }
  deleteAvailability(id) {
    return new Promise(((resolve, reject) => {
      this.client.post(`availabilities/${id}/cancel`, {}).then(response => {
        resolve(response);
      }).catch(e => {
        reject(e);
      });
    }));
  }
}

exports.MentornityBridgeApi = MentornityBridgeApi;
exports.commonUserInfoFields = commonUserInfoFields;
exports.convertMentornityFieldToDevingenField = convertMentornityFieldToDevingenField;
exports.generateCalendarConfig = generateCalendarConfig;
exports.getEmbeddedTranslation = getEmbeddedTranslation;
exports.legacyProfileFields = legacyProfileFields;
exports.skills = skills;
exports.skillsEN = skillsEN;
