// instances.js — список инстансов, выбор сервиса, toggle операций
let svcInstances=[], selectedInst=null, selectedOp=null;
let currentSvcId=(window.APP&&window.APP.firstServiceId)||1;
let currentSvcName='';
let currentSvcShort='';
let busy=false;
const AUTOTEST_PREFIX='autotest-';
async function selectService(svcId){
if(busy) return;
currentSvcId=svcId;
selectedInst=null; selectedOp=null; stopPoll();
document.getElementById('params-area').style.display='none';
document.querySelectorAll('.stages-box').forEach(e=>e.remove());
document.querySelectorAll('.svc-item').forEach(e=>e.classList.remove('active'));
const svcEl=document.querySelector(`.svc-item[onclick*="${svcId}"]`);
if(svcEl) svcEl.classList.add('active');
try{
const r=await fetch('/api/operations/'+svcId);
const d=await r.json();
svcInstances=d.instances||[];
currentSvcName=d.svc||'';
currentSvcShort=d.svcShort||'';
const btnSpan=document.querySelector('#create-btn-area span');
if(btnSpan) btnSpan.textContent='+ Создать новый инстанс '+(currentSvcName||'сервиса');
renderInstances();
}catch(e){document.getElementById('inst-list').innerHTML='Ошибка загрузки';}
}
function renderInstances(){
let html='';
svcInstances.forEach(i=>{
const status=i.status||i.explainedStatus||'?';
const sc=status==='running'?'badge-success':'';
html+=`
${_esc(i.displayName)}
${_esc(i.svc||'')}
${_esc(status)}
`;
html+=``;
});
document.getElementById('inst-list').innerHTML=html;
}
async function refreshInstances(){
try{
const r=await fetch('/api/operations/'+currentSvcId);
const d=await r.json();
svcInstances=d.instances||[];
renderInstances();
}catch(e){}
}
async function toggleInstance(iuid){
if(busy) return;
selectedInst=iuid; stopPoll();
document.querySelectorAll('[data-iuid]').forEach(e=>e.classList.toggle('active',e.dataset.iuid===iuid));
document.getElementById('params-area').style.display='none';
const opsEl=document.getElementById('ops-'+iuid);
if(opsEl.classList.contains('open')){opsEl.classList.remove('open');return;}
document.querySelectorAll('.inst-ops').forEach(e=>e.classList.remove('open'));
const inst=svcInstances.find(x=>x.instanceUid===iuid);
const svcId=inst?inst.serviceId:currentSvcId;
try{
const r=await fetch('/api/operations/'+svcId);
const d=await r.json();
let ops=(d.operations||[]).filter(o=>o.operation!=='reconcile'&&o.operation!=='create');
if(inst&&(inst.status||inst.explainedStatus)==='not created'){
ops=ops.filter(o=>o.operation==='delete');
}
opsEl.innerHTML=ops.map(o=>
``
).join('');
opsEl.classList.add('open');
}catch(e){opsEl.innerHTML='Ошибка загрузки';opsEl.classList.add('open');}
}
function opClass(opName){
if(opName==='modify') return 'op-btn-modify';
if(opName==='suspend') return 'op-btn-suspend';
if(opName==='resume') return 'op-btn-resume';
if(opName==='delete') return 'op-btn-delete';
if(opName==='redeploy') return 'op-btn-redeploy';
return '';
}
// Инициализация
selectService(currentSvcId);