<template>
    <div>
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Ghép chuỗi</h4>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="javascript:void(0);">Trang chủ</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Ghép chuỗi</li>
                </ol>
            </div>
        </div>
        <div class="row row-sm">
            <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin">
                <div class="card card-search shadow-none">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-5">
                                <!-- Input section -->
                                <div class="mb-4">
                                    <label for="inputArea" class="form-label fw-bold">Nhập dữ liệu của bạn:</label>
                                    <textarea id="inputArea" v-model="inputText"
                                        placeholder="Nhập dữ liệu chưa có dấu phân tách (mỗi giá trị trên một dòng)"
                                        class="form-control" rows="30"></textarea>
                                </div>
                            </div>
                            <div class="col-md-2 mt-5">
                                <div class="form-group">
                                    <label class="form-label fw-bold">Dấu phân tách đầu ra:</label>
                                    <div class="d-flex align-items-center">
                                        <select v-model="outputDelimiterType" class="form-select">
                                            <option value=",">Dấu phẩy (,)</option>
                                            <option value=";">Chấm phẩy (;)</option>
                                            <option value="|">Gạch đứng (|)</option>
                                            <option value=" ">Khoảng trắng</option>
                                            <option value="\n">Xuống dòng</option>
                                            <option value="custom">Tùy chỉnh</option>
                                        </select>
                                        <input v-if="outputDelimiterType === 'custom'" v-model="customDelimiter"
                                            type="text" placeholder="Nhập dấu phân tách" class="form-control ms-2" />
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="form-label fw-bold">Tách dữ liệu đầu vào theo:</label>
                                    <select v-model="explodeBy" class="form-select">
                                        <option value="newline">Dòng mới</option>
                                        <option value="space">Khoảng trắng</option>
                                        <option value="comma">Dấu phẩy</option>
                                        <option value="semicolon">Chấm phẩy</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <!-- Quote type -->
                                    <label class="form-label fw-bold">Thêm dấu nháy:</label>
                                    <select v-model="quoteType" class="form-select">
                                        <option value="none">Không</option>
                                        <option value="double">Nháy kép ""</option>
                                        <option value="single">Nháy đơn ''</option>
                                    </select>
                                </div>
                                <button @click="convert" class="btn btn-block btn-primary fw-bold">
                                    Chuyển đổi
                                </button>
                                <div class="form-group mt-2">
                                    <input type="checkbox" v-model="tidyUp" class="form-check-input mg-l-10"
                                        id="tidyUpCheckbox" />
                                    <label class="form-check-label fw-bold mg-l-30 mg-t-2" for="tidyUpCheckbox">Xóa
                                        xuống dòng trong
                                        kết quả?</label>
                                </div>
                                <div class="form-group">
                                    <input type="checkbox" v-model="removeDuplicates" class="form-check-input mg-l-10"
                                        id="removeDuplicatesCheckbox" />
                                    <label class="form-check-label fw-bold mg-l-30 mg-t-2"
                                        for="removeDuplicatesCheckbox">Loại bỏ giá
                                        trị
                                        trùng
                                        lặp?</label>
                                </div>
                                <div class="form-group">
                                    <label class="form-label fw-bold">Bọc từng giá trị bằng thẻ:</label>
                                    <div class="d-flex">
                                        <input v-model="recordOpenTag" type="text" placeholder="Thẻ mở, ví dụ <strong>"
                                            class="form-control me-2" />
                                        <input v-model="recordCloseTag" type="text"
                                            placeholder="Thẻ đóng, ví dụ </strong>" class="form-control" />
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="form-label fw-bold">Thêm xuống dòng sau mỗi:</label>
                                    <div class="input-group">
                                        <input type="number" min="0" v-model.number="interval" class="form-control" />
                                        <span class="input-group-text">giá trị (0 không chia)</span>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="form-label fw-bold">Bọc nhóm bởi thẻ:</label>
                                    <div class="d-flex">
                                        <input v-model="intervalOpenTag" type="text" placeholder="Thẻ mở cho nhóm"
                                            class="form-control me-2" />
                                        <input v-model="intervalCloseTag" type="text" placeholder="Thẻ đóng cho nhóm"
                                            class="form-control" />
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-5">
                                <div class="form-group">
                                    <label for="outputArea" class="form-label fw-bold">Kết quả:</label>
                                    <textarea id="outputArea" v-model="outputText" class="form-control"
                                        rows="30"></textarea>
                                </div>

                            </div>

                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>


</template>
<script setup>
import { ref } from 'vue';

// Reactive data definitions
const inputText = ref('');
const outputText = ref('');

// Options
const outputDelimiterType = ref(',');
const customDelimiter = ref('');
const explodeBy = ref('newline');
const tidyUp = ref(true);
const removeDuplicates = ref(true);
const quoteType = ref('none');
const recordOpenTag = ref('');
const recordCloseTag = ref('');
const interval = ref(0);
const intervalOpenTag = ref('');
const intervalCloseTag = ref('');

/**
 * Determine the delimiter string for output based on user selection.
 */
function getOutputDelimiter() {
    return outputDelimiterType.value === 'custom'
        ? customDelimiter.value
        : outputDelimiterType.value;
}

/**
 * Parse the raw input text into an array of values based on explodeBy.
 */
function parseInput(text) {
    let delimiterRegex;
    switch (explodeBy.value) {
        case 'newline':
            delimiterRegex = /[\r\n]+/;
            break;
        case 'space':
            delimiterRegex = /\s+/;
            break;
        case 'comma':
            delimiterRegex = /,+/;
            break;
        case 'semicolon':
            delimiterRegex = /;+/;
            break;
        default:
            delimiterRegex = /[\r\n]+/;
    }
    // Split and trim each value
    let values = text.split(delimiterRegex).map(v => v.trim()).filter(v => v.length > 0);
    // Remove duplicates if requested
    if (removeDuplicates.value) {
        values = Array.from(new Set(values));
    }
    return values;
}

/**
 * Apply quoting and tag wrapping to each value.
 */
function transformValue(value) {
    let result = value;
    // Apply quotes
    if (quoteType.value === 'double') {
        result = `"${result}"`;
    } else if (quoteType.value === 'single') {
        result = `'${result}'`;
    }
    // Apply record tags
    if (recordOpenTag.value || recordCloseTag.value) {
        result = `${recordOpenTag.value ?? ''}${result}${recordCloseTag.value ?? ''}`;
    }
    return result;
}

/**
 * Build the output string from processed values using interval grouping and delimiter.
 */
function buildOutput(values) {
    const delim = getOutputDelimiter();
    // If interval is zero or less, treat as no grouping
    const groupSize = interval.value && interval.value > 0 ? interval.value : values.length;
    const groups = [];
    for (let i = 0; i < values.length; i += groupSize) {
        const chunk = values.slice(i, i + groupSize);
        const joined = chunk.join(delim);
        // Wrap each group with interval tags if provided
        if (intervalOpenTag.value || intervalCloseTag.value) {
            groups.push(
                `${intervalOpenTag.value ?? ''}${joined}${intervalCloseTag.value ?? ''}`
            );
        } else {
            groups.push(joined);
        }
    }
    let output = groups.join('\n');
    // Tidy up by removing newline characters if requested
    if (tidyUp.value) {
        output = output.replace(/[\r\n]+/g, '');
    }
    return output;
}

/**
 * Main conversion function triggered by button click.
 */
function convert() {
    const rawValues = parseInput(inputText.value);
    const transformed = rawValues.map(transformValue);
    outputText.value = buildOutput(transformed);
}
</script>

<style scoped>
.delim-component {
    max-width: 800px;
    margin: auto;
    font-family: Arial, sans-serif;
}

.options-section label {
    display: inline-block;
    margin-bottom: 0.5rem;
}
</style>