const dataKey = 'rightsStateV2';

var state = {
  accessProject: undefined,
  accessDefaultColumn: undefined,
  accessRestrictColumn: undefined,
  boards: {} // {[boardId]: userId[]}
};

const styles = {
  chatCnt: {
    background: '#f4f5f5',
    margin: '16px',
    padding: '16px',
    borderRadius: '2px',
    border: '1px solid #bbb'
  },
  userSticker: {
    display: 'inline-block',
    margin: '4px 4px 0 0'
  },
  withAccessBtn: {
    color: '#2b5',
    display: 'inline-block',
    margin: '0 4px',
    cursor: 'pointer'
  },
  noAccessBtn: {
    color: '#999',
    display: 'inline-block',
    margin: '0 4px',
    cursor: 'pointer'
  },
  userName: {
    display: 'inline-block'
  },
  userAva: {
    margin: '0 4px -2px 0',
    display: 'inline-block'
  }
};

function init() {
  const data = Current.company.getData();
  if (data[dataKey]) {
    return;
  }
  const proj = Current.company.add('Права пользователей');
  const board = proj.add('По доскам');
  const accDef = board.add('Доступ по умолчанию');
  const accRes = board.add('Ограниченный доступ');

  data[dataKey] = {
    accessProjectId: proj.id,
    accessDefaultColumnId: accDef.id,
    accessRestrictColumnId: accRes.id,
    boards: {}
  };

  Current.company.setData(data);
}
function loadState() {
  const data = Current.company.getData();
  const dataState = data[dataKey];
  state.accessProject = Items.get(dataState.accessProjectId);
  state.accessDefaultColumn = Items.get(dataState.accessDefaultColumnId);
  state.accessRestrictColumn = Items.get(dataState.accessRestrictColumnId);
  state.boards = JSON.parse(JSON.stringify(dataState.boards || {}));
  console.log('load', state);
}

function saveState() {
  const data = Current.company.getData();
  const dataState = data[dataKey];
  dataState.accessProjectId = state.accessProject.id;
  dataState.accessDefaultColumnId = state.accessDefaultColumn.id;
  dataState.accessRestrictColumnId = state.accessRestrictColumn.id;
  dataState.boards = JSON.parse(JSON.stringify(state.boards || {}));
  Current.company.setData(data);
  console.log('save', data);
}

function isNotInAccessProj(item) {
  if (item.type === 'Company') {
    return true;
  } else if (item.type === 'Project') {
    return item.id !== state.accessProject.id;
  } else {
    return isNotInAccessProj(item.up());
  }
}

function hideStickers() {
  if (Current.project && Current.project.id === state.accessProject.id) {
    UI.components.stickerPanel.style = {display: 'none'};
  } else {
    UI.components.stickerPanel.style = {display: 'block'};
  }
}

function getPath(board) {
  return board.up().name + ' » ' + board.name;
}

function isDeleted(item) {
  if (item.deleted) {
    return true;
  }
  if (item.type === 'Company') {
    return false;
  }
  return isDeleted(item.up());
}

function syncTasks() {
  const ix = {}; // boardId -> taskId
  const drawnDefault = {}; // boardId -> true
  const drawnRestricted = {}; // boardId -> true
  state.accessDefaultColumn.list().forEach(t => {
    const data = t.getData();
    if (!data.boardId) {
      t.deleted = true;
    } else {
      const b = Items.get(data.boardId);
      if (!b || isDeleted(b)) {
        t.deleted = true;
      } else {
        drawnDefault[data.boardId] = true;
      }
    }
  });
  state.accessRestrictColumn.list().forEach(t => {
    const data = t.getData();
    if (!data.boardId) {
      t.deleted = true;
    } else {
      const b = Items.get(data.boardId);
      if (!b || isDeleted(b)) {
        t.deleted = true;
      } else {
        drawnRestricted[data.boardId] = true;
      }
    }
  });
  Current.company.list().forEach(p => {
    if (p.id !== state.accessProject.id) {
      p.list().forEach(b => {
        if (!drawnDefault[b.id] && !drawnRestricted[b.id]) {
          const t = state.accessDefaultColumn.add(getPath(b));
          t.setData({boardId: b.id});
        }
      });
    }
  });

  loadState();
  let changed = false;
  Object.keys(state.boards).forEach(id => {
    if (!drawnRestricted[id]) {
      delete state.boards[id];
      changed = true;
    }
  });
  Object.keys(drawnRestricted).forEach(id => {
    if (!state.boards[id]) {
      state.boards[id] = [];
      changed = true;
    }
  });
  if (changed) {
    saveState();
  }
}

if (Current.user.isAdmin) {
  init();
}
loadState();

if (Current.user.isAdmin) {
  syncTasks();
}

function drawChat() {
  UI.components.chat.clear();
  if (!Current.chat || isNotInAccessProj(Current.chat)) {
    return;
  }
  const data = Current.chat.getData();
  const boardId = data.boardId;
  if (!boardId || !state.boards[boardId]) {
    return;
  }
  const cnt = UI.panel();
  cnt.style = styles.chatCnt;
  UI.components.chat.add(cnt);
  const conf = state.boards[boardId];
  const drawRow = u => {
    const row = UI.panel();
    cnt.add(row);
    const uAva = UI.user(u);
    uAva.style = styles.userAva;
    row.add(uAva);
    const uName = UI.text(u.name);
    uName.style = styles.userName;
    row.add(uName);
    if (conf.indexOf(u.id) > -1) {
      const btn = UI.text('Есть доступ');
      btn.style = styles.withAccessBtn;
      row.add(btn);
      btn.onClick = () => {
        loadState();
        if (state.boards[boardId]) {
          state.boards[boardId] = state.boards[boardId].filter(
            uid => uid !== u.id
          );
          saveState();
        }
      };
    } else {
      const btn = UI.text('Нет доступа');
      btn.style = styles.noAccessBtn;
      btn.onClick = () => {
        loadState();
        if (state.boards[boardId]) {
          state.boards[boardId] = [
            ...new Set([...state.boards[boardId], u.id])
          ];
          saveState();
        }
      };
      row.add(btn);
    }
  };
  Users.listAll().forEach(u => drawRow(u));
}

function drawTasks() {
  if (!Current.project || Current.project.id !== state.accessProject.id) {
    return;
  }
  state.accessDefaultColumn.list().forEach(t => t.ui.clear());
  state.accessRestrictColumn.list().forEach(t => {
    t.ui.clear();
    const data = t.getData();
    const boardId = data.boardId;
    if (!boardId) {
      return;
    }
    const cnt = UI.panel();
    t.ui.add(cnt);
    const users = state.boards[boardId];
    if (!users) {
      return;
    }
    users.forEach(uid => {
      const u = Users.get(uid);
      const uui = UI.user(u);
      uui.style = styles.userSticker;
      cnt.add(uui);
    });
  });
}

drawChat();
Current.onChatChange = drawChat;
drawTasks();
Current.onBoardChange = drawTasks;
hideStickers();
Current.onProjectChange = hideStickers;

Items.allowDelete = isNotInAccessProj;
Items.allowAdd = isNotInAccessProj;
Items.allowRename = isNotInAccessProj;

Items.onUpdate = () => {
  loadState();
  syncTasks();
  drawChat();
  drawTasks();
};
Items.allowDrag = item => {
  return isNotInAccessProj(item) || item.type === 'Task';
};

Items.isHidden = item => {
  if (item.type === 'Board') {
    const users = state.boards[item.id];
    return users && users.indexOf(Current.user.id) === -1;
  } else if (item.type === 'Project') {
    return (
      item.list().filter(b => {
        const users = state.boards[b.id];
        return !(users && users.indexOf(Current.user.id) === -1);
      }).length === 0
    );
  } else {
    return false;
  }
};

Items.onMove = (item, from, to) => {
  console.log('onMove', item, from, to);
  if (!isNotInAccessProj(item)) {
    console.log(item);
    if (item.type === 'Task') {
      if (
        state.accessDefaultColumn.id !== from.id &&
        state.accessRestrictColumn.id !== from.id
      ) {
        Notifier.warn('Нельзя переносить');
        return false;
      } else if (
        state.accessDefaultColumn.id !== to.id &&
        state.accessRestrictColumn.id !== to.id
      ) {
        Notifier.warn('Нельзя переносить');
        return false;
      } else {
        setTimeout(() => syncTasks(), 500);
        return true;
      }
    } else {
      Notifier.warn('Нельзя переносить');
      return false;
    }
  } else {
    return true;
  }
};
