//
// Copyright © 2020 Anticrm Platform Contributors.
//
// Licensed under the Eclipse Public License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. You may
// obtain a copy of the License at https://www.eclipse.org/legal/epl-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//

/* eslint-env jest */
import { htmlToJSON, jsonToHTML } from '@hcengineering/text'
import { parseMessageMarkdown, serializeMessage } from '..'
import { defaultExtensions } from '../extensions'

import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'
import { dirname, join } from 'path'
import { gunzipSync } from 'zlib'
import { calcSørensenDiceCoefficient, isMarkdownsEquals } from '../compare'

const refUrl: string = 'ref://'
const imageUrl: string = 'http://localhost'

const markdownSamples = JSON.parse(gunzipSync(readFileSync('./src/markdown/__tests__/markdown.json.gz')).toString())

const testStrings = Array.from((markdownSamples)).reduce((decodedStrings: { repoName: string, markdownSource: string, markdown: string }[], { markdownEncoded, markdownEncoding, repoName, markdownSource }: any) => {
  if (markdownEncoding === 'base64') {
    decodedStrings.push({ repoName, markdownSource, markdown: atob(markdownEncoded) })
  }

  return decodedStrings
}, [])

describe('server', () => {
  it('test-all', () => {
    let i = 0
    const dta = testStrings
    let errors: number = 0
    let minK = 100
    let minKi = 0
    const result = []
    for (const sample of dta) {
      try {
        const fileName = join('src', 'markdown', '__tests__', 'markdowns', `${i}${sample.repoName}`, sample.markdownSource)

        const json = parseMessageMarkdown(sample.markdown, refUrl, imageUrl)

        const html = jsonToHTML(json, defaultExtensions)

        const json2 = htmlToJSON(html, defaultExtensions)
        const newMarkdown = serializeMessage(json2, refUrl, imageUrl)
        const k = calcSørensenDiceCoefficient(sample.markdown, newMarkdown) * 100
        minK = Math.min(k, minK)
        if (minK === k) {
          minKi = i
        }
        const equals = isMarkdownsEquals(sample.markdown, newMarkdown)
        if (k < 50) {
          if (!existsSync(dirname(fileName))) {
            mkdirSync(dirname(fileName), { recursive: true })
          }
          writeFileSync(fileName + '_source.md', sample.markdown)
          writeFileSync(fileName + '_target.md', newMarkdown)
        }
        result.push(`${fileName}: ${k} ${equals}`)
      } catch (e) {
        errors++
        // console.error(e)
      }
      i++
    }
    console.log('Result', result.join('\n'))
    console.log('MinK:', minK, minKi)
    console.log('Errors:', errors)
  })
})
