import { apiService } from './api.service';
import { underscoreToCamelcase } from './utils/camelcase-convert';
import axios from 'axios';
import moment from 'moment';

const format = "YYYY-MM-DD HH:mm:ss";

export const repoService = {
  async getFileList(
    projectId,
    refName,
    path,
    withCommit
  ) {
    return (await apiService.get(
      `/webapi/projects/42422/repository/tree`,
      {
        refName,
        path,
        withCommit,
      }
    ))
  },

  async getTreeEntry(projectId, refName, path) {
    return (await apiService.get(
      `/api/v3/projects/42422/repository/tree_entry`,
      {
        refName,
        path,
      }
    ))
  },

  async getCodeSymbols(projectId, ref, filepath) {
    return await apiService.get(
      `/api/v3/projects/42422/repository/file_symbols/${encodeURIComponent(
        ref
      )}/`,
      {
        filepath,
      }
    );
  },

  async getCodeBlame(projectsId, owner, params) {
    const res = await axios.get(`/v1/${owner}/${projectsId}/blame.json`, { params });
    let blame_parts = underscoreToCamelcase(res.data.blame_parts);
    let blameParts = [];
    for (const item of blame_parts) {
      let blamePart = {
        commit: {
          author: item.commit.author,
          // authorEmail: "taian.lta@test.com",
          authorName: item.commit.author.name,
          authoredDate: moment(new Date(item.commit.authoredTime * 1000)).format(format),
          committedDate: moment(new Date(item.commit.committedTime * 1000)).format(format),
          committer: item.commit.committer,
          // committerEmail: "taian.lta@test.com",
          committerName: item.commit.committer.name,
          createdAt: moment(new Date(item.commit.createdTime * 1000)).format(format),
          id: item.commit.sha,
          message: item.commit.commitMessage,
          // parentIds: null,
          // shortId: "7c501a19",
          title: item.commit.commitMessage,
          // treeHash: null,
        },
        lines: [{
          currentNumber: item.currentNumber,
          effectLine: item.effectLine,
        }]
      };
      blameParts.push(blamePart);
    }
    return blameParts;
  },
};
