<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SVGにテキストを描画</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;700&display=swap');

        body {
            display: flex;
            height: 100vh;
            margin: 0;
            font-family: 'Noto Sans', sans-serif;
        }

        #svgContainer {
            width: 70%;
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: #f0f0f0;
            position: relative;
            overflow: hidden;
        }

        svg {
            width: 100%; /* 表示サイズ */
            height: auto; /* 高さはアスペクト比に基づく */
            max-width: 100%;
            max-height: 100%;
        }

        #formContainer {
            width: 30%;
            padding: 20px;
            box-sizing: border-box;
            overflow-y: auto;
            background-color: #ffffff;
        }

        #formContainer h1 {
            font-size: 1.5em;
            margin-bottom: 20px;
        }

        #textInputs div {
            margin-bottom: 10px;
        }

        input[type="number"] {
            width: 60px;
        }

        input[type="checkbox"] {
            margin-left: 5px;
        }

        #fileButtons {
            display: flex;
            flex-direction: column;
            margin-bottom: 20px;
        }

        #fileButtons button, #fileButtons input[type="file"] {
            margin-bottom: 10px;
        }

        #alertMessage {
            display: none;
            background-color: #f8d7da;
            color: #721c24;
            padding: 10px;
            margin-bottom: 20px;
            border: 1px solid #f5c6cb;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <!-- 左側のSVGを表示 -->
    <div id="svgContainer">
        <object id="mySVG" data="template.svg" type="image/svg+xml" style="width: 100%; height: auto;"></object>
    </div>

    <!-- 右側のフォーム類 -->
    <div id="formContainer">
        <div id="fileButtons">
            <!-- SVGファイルの入力 -->
            <input type="file" id="svgFileInput" accept=".svg" onchange="loadSVG(event)">
            <button onclick="saveToSVG()">SVGとして保存</button>

            <!-- CSVファイルの入力 -->
            <input type="file" id="csvFileInput" accept=".csv" onchange="loadFromCSV(event)">
            <button onclick="saveToCSV()">CSVとして保存</button>
        </div>

        <!-- エラーメッセージの表示 -->
        <div id="alertMessage">SVGファイルを選択してください。</div>

        <h1>SVGにテキストを描画するツール</h1>

        <!-- フォーム -->
        <form id="textForm" style="margin-top: 20px;">
            <div id="textInputs">
                <!-- JavaScriptで入力フィールドを動的に生成 -->
            </div>
        </form>
    </div>

    <script>
        const textCount = 10; // テキストの数
        let svgFileName = ''; // 読み込んだSVGファイル名を保持

        function createTextInputs() {
            const textInputsDiv = document.getElementById('textInputs');

            for (let i = 1; i <= textCount; i++) {
                const textDiv = document.createElement('div');
                textDiv.innerHTML = `
                    <h3>テキスト${i}</h3>
                    <label for="inputText${i}">テキスト${i}:</label>
                    <input type="text" id="inputText${i}" name="inputText${i}" value="テキスト${i}" oninput="updateSVG()">
                    
                    <label for="xCoord${i}">X座標${i}:</label>
                    <input type="number" id="xCoord${i}" name="xCoord${i}" value="${100 * i}" oninput="updateSVG()">
                    
                    <label for="yCoord${i}">Y座標${i}:</label>
                    <input type="number" id="yCoord${i}" name="yCoord${i}" value="${100}" oninput="updateSVG()">

                    <label for="fontSize${i}">フォントサイズ:</label>
                    <input type="number" id="fontSize${i}" name="fontSize${i}" value="20" oninput="updateSVG()">

                    <label for="isBold${i}">ボールド:</label>
                    <input type="checkbox" id="isBold${i}" name="isBold${i}" onchange="updateSVG()">
                `;
                textInputsDiv.appendChild(textDiv);
            }
        }

        function loadSVG(event) {
            const file = event.target.files[0];
            svgFileName = file.name; // SVGファイル名を保持
            const reader = new FileReader();

            reader.onload = function(e) {
                const svgContainer = document.getElementById('mySVG');
                svgContainer.innerHTML = e.target.result;

                updateSVG(); // テキストを再描画
            };

            reader.readAsText(file);
        }

        function updateSVG() {
            const svgContainer = document.getElementById('mySVG').contentDocument;
            const svgRoot = svgContainer.documentElement;

            // 既存のテキスト要素をクリア
            while (svgRoot.lastChild && svgRoot.lastChild.tagName === "text") {
                svgRoot.removeChild(svgRoot.lastChild);
            }

            // 各テキストをSVGに描画
            for (let i = 1; i <= textCount; i++) {
                const inputText = document.getElementById(`inputText${i}`).value;
                const xCoord = parseInt(document.getElementById(`xCoord${i}`).value);
                const yCoord = parseInt(document.getElementById(`yCoord${i}`).value);
                const fontSize = parseInt(document.getElementById(`fontSize${i}`).value);
                const isBold = document.getElementById(`isBold${i}`).checked;

                const textElement = document.createElementNS("http://www.w3.org/2000/svg", "text");
                textElement.setAttribute("x", xCoord);
                textElement.setAttribute("y", yCoord);
                textElement.setAttribute("font-family", "Noto Sans");
                textElement.setAttribute("font-size", fontSize);
                textElement.setAttribute("fill", "black");
                textElement.setAttribute("font-weight", isBold ? "bold" : "normal");
                textElement.textContent = inputText;

                svgRoot.appendChild(textElement);
            }
        }

        function saveToSVG() {
            const svgContainer = document.getElementById('mySVG').contentDocument.documentElement;
            const serializer = new XMLSerializer();
            const svgData = serializer.serializeToString(svgContainer);

            const svgBlob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' });
            const svgUrl = URL.createObjectURL(svgBlob);

            const downloadLink = document.createElement("a");
            downloadLink.href = svgUrl;
            downloadLink.download = "output.svg";
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);
        }

        function saveToCSV() {
            let csvContent = `SVGファイル,${svgFileName}\nテキスト, X座標, Y座標, フォントサイズ, ボールド\n`;

            for (let i = 1; i <= textCount; i++) {
                const inputText = document.getElementById(`inputText${i}`).value;
                const xCoord = document.getElementById(`xCoord${i}`).value;
                const yCoord = document.getElementById(`yCoord${i}`).value;
                const fontSize = document.getElementById(`fontSize${i}`).value;
                const isBold = document.getElementById(`isBold${i}`).checked ? "bold" : "normal";
                csvContent += `${inputText},${xCoord},${yCoord},${fontSize},${isBold}\n`;
            }

            const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            const url = URL.createObjectURL(blob);
            const link = document.createElement("a");
            link.setAttribute("href", url);
            link.setAttribute("download", "text_positions.csv");
            document.body.appendChild(link);

            link.click();
            document.body.removeChild(link);
        }

        function loadFromCSV(event) {
            const file = event.target.files[0];
            const reader = new FileReader();
            reader.onload = function(e) {
                const csvContent = e.target.result;
                const rows = csvContent.split("\n");
                
                // SVGファイル名を取得
                svgFileName = rows[0].split(",")[1].trim();

                // SVGファイルを再度読み込む
                if (svgFileName) {
                    loadSVGFileByName(svgFileName);
                }

                rows.slice(2).forEach((row, index) => {
                    if (index < textCount) {
                        const columns = row.split(",");
                        if (columns.length >= 5) {
                            document.getElementById(`inputText${index + 1}`).value = columns[0];
                            document.getElementById(`xCoord${index + 1}`).value = columns[1];
                            document.getElementById(`yCoord${index + 1}`).value = columns[2];
                            document.getElementById(`fontSize${index + 1}`).value = columns[3];
                            document.getElementById(`isBold${index + 1}`).checked = columns[4].trim() === "bold";
                        }
                    }
                });
                updateSVG();
            };
            reader.readAsText(file);
        }

        function loadSVGFileByName(fileName) {
            fetch(fileName)
                .then(response => {
                    if (response.ok) {
                        return response.text();
                    } else {
                        throw new Error('SVGファイルが見つかりません');
                    }
                })
                .then(svgData => {
                    const svgContainer = document.getElementById('mySVG');
                    svgContainer.innerHTML = svgData;
                    updateSVG();
                })
                .catch(error => {
                    console.error('Error loading SVG:', error);
                    showAlert();
                });
        }

        function showAlert() {
            const alertMessage = document.getElementById('alertMessage');
            alertMessage.style.display = 'block';
            setTimeout(() => {
                alertMessage.style.display = 'none';
            }, 5000);
        }

        window.onload = function() {
            createTextInputs(); // 入力フィールドの生成

            const svgObject = document.getElementById('mySVG');
            svgObject.addEventListener('load', () => {
                updateSVG(); // 初期表示
            });

            svgObject.addEventListener('error', showAlert); // エラー発生時にアラート表示
        };
    </script>
</body>
</html>
