import R from "ramda"

import {execSync} from "child_process"

import {startServer} from "../webpack"
import {createPullRequestOnProd, authenticate} from "../services/github"

import {pipeAsync} from "./common"

import {getCurrentBranch, getUikitsList, getOriginBranchesHashes} from "./branches"

export const runServer = async ({type} = {}) => {
  const hashes = getOriginBranchesHashes()
  const uikitsList = R.pipe(
    getUikitsList,
    R.map(R.juxt([R.identity, (uikit) => hashes[`uikit/${uikit}/dev`]])),
    R.fromPairs,
  )()
  const blockUikitId = R.pipe(
    getCurrentBranch,
    R.split(`/`),
    R.cond([
      [R.pipe(R.nth(0), R.equals(`w`)), R.always(`wireframe-1`)],
      [
        R.pipe(R.nth(0), R.equals(`d`)),
        R.pipe(R.nth(1), R.when(R.complement(R.flip(R.has)(uikitsList)), R.always(R.nth(0, uikitsList)))),
      ],
    ]),
  )()
  await startServer({uikitsList, blockUikitId, type})
}

export const publishBlock = pipeAsync(
  getCurrentBranch,
  R.ifElse(
    R.pipe(
      R.split(`/`),
      R.allPass([R.pipe(R.nth(0), R.flip(R.contains)([`w`, `d`])), R.pipe(R.nth(3), R.equals(`dev`))]),
    ),
    (name) =>
      pipeAsync(() => execSync(`git push --set-upstream origin ${name}`), () => createPullRequestOnProd(name))(),
    () => console.log(`You must be at wireframe or design branch`),
  ),
)

export const initialAuthenticate = R.pipe(
  R.always({
    type: process.env.GITHUB_AUTH_TYPE,
    username: process.env.GITHUB_USERNAME,
    password: process.env.GITHUB_PASSWORD,
    token: process.env.GITHUB_TOKEN,
  }),
  R.reject(R.isNil),
  R.when(R.pipe(R.prop(`type`), R.anyPass([R.equals(`basic`), R.equals(`token`)])), authenticate),
)
