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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648

import {CM_TO_PX} from "../constants";
import {roundNumber} from "./utils";

// eslint-disable-next-line
import StaffToken from "./staffToken";
// eslint-disable-next-line
import * as LilyNotation from "../lilyNotation";
import pick from "../pick";



interface SheetMarkingData {
	id: string;
	text: string;
	x: number;
	y: number;
	cls: string;
}


export interface SheetMeasure {
	index: number;
	tokens: StaffToken[];
	headX: number;
	lineX?: number;
	matchedTokens?: StaffToken[];	// for baking mode
	noteRange: {
		begin: number,
		end: number,
	};

	class?: {[key: string]: boolean};
};


export interface SheetStaff {
	measures: SheetMeasure[];
	tokens: StaffToken[];

	markings?: Partial<SheetMarkingData>[];

	// the third staff line Y coordinate value
	//	The third staff line Y supposed to be zero, but regarding to the line stroke width,
	//	there is some error for original values in SVG document (which erased by coordinate rounding).
	yRoundOffset?: number; // 0.0657 for default

	x: number;
	y: number;
	top?: number;
	headWidth?: number;
};


export interface SheetSystem {
	index?: number;
	pageIndex?: number;
	measureIndices?: [number, number][];	// [end_x, index]
	staves: SheetStaff[];
	tokens: StaffToken[];

	x: number;
	y: number;
	width?: number;
	top: number;
	bottom: number;
};


export interface SheetPage {
	width: string;
	height: string;
	viewBox: {
		x: number,
		y: number,
		width: number,
		height: number,
	};

	systems: SheetSystem[];
	tokens: StaffToken[];

	hidden?: boolean;

	// DEPRECATED
	rows?: SheetSystem[];
};


/*const ALTER_PREFIXES = {
	[-2]: "\u266D\u266D",
	[-1]: "\u266D",
	[0]: "\u266E",
	[1]: "\u266F",
	[2]: "\uD834\uDD2A",
};*/

// char codes defined in music font
const ALTER_PREFIXES = {
	[-2]: "\ue02a",
	[-1]: "\ue021",
	[0]: "\ue01d",
	[1]: "\ue013",
	[2]: "\ue01c",
};


let sheetMarkingIndex = 0;


class SheetMarking {
	alter?: number;
	index: number;	// as v-for key

	id?: string;
	text?: string;
	x?: number;
	y?: number;
	cls?: string;


	constructor (fields: Partial<SheetMarkingData>) {
		this.index = sheetMarkingIndex++;
		Object.assign(this, fields);
	}


	get alterText (): string {
		return Number.isInteger(this.alter) ? ALTER_PREFIXES[this.alter] : null;
	}
};


const parseUnitExp = exp => {
	if (/[\d.]+mm/.test(exp)) {
		const [value] = exp.match(/[\d.]+/);
		return Number(value) * 0.1 * CM_TO_PX;
	}

	return Number(exp);
};


type MeasureLocationTable = {[key: number]: {[key: number]: number}};


const cc = <T>(arrays: T[][]): T[] => [].concat(...arrays);


class SheetDocument {
	pages: SheetPage[];


	constructor (fields: Partial<SheetDocument>, {initialize = true} = {}) {
		Object.assign(this, fields);

		if (initialize)
			this.updateTokenIndex();
	}


	get systems (): SheetSystem[] {
		return [].concat(...this.pages.map(page => page.systems));
	}


	// DEPRECATED
	get rows (): SheetSystem[] {
		return this.systems;
	}


	get trackCount (): number{
		return Math.max(...this.systems.map(system => system.staves.length), 0);
	}


	get pageSize (): {width: number, height: number} {
		const page = this.pages && this.pages[0];
		if (!page)
			return null;

		return {
			width: parseUnitExp(page.width),
			height: parseUnitExp(page.height),
		};
	}


	updateTokenIndex () {
		// remove null pages for broken document
		this.pages = this.pages.filter(page => page);

		this.pages.forEach((page, index) => page.systems.forEach(system => system.pageIndex = index));

		let rowMeasureIndex = 1;

		this.systems.forEach((system, index) => {
			system.index = index;
			system.width = system.tokens.concat(...system.staves.map(staff => staff.tokens))
				.reduce((max, token) => Math.max(max, token.x), 0);

			system.measureIndices = [];

			system.staves = system.staves.filter(s => s);
			system.staves.forEach((staff, t) => {
				staff.measures.forEach((measure, i) => {
					measure.index = rowMeasureIndex + i;
					measure.class = {};

					measure.tokens.forEach(token => {
						token.system = index;
						token.measure = measure.index;
						token.endX = measure.noteRange.end;
					});

					measure.lineX = measure.lineX || 0;
					if (i < staff.measures.length - 1)
						staff.measures[i + 1].lineX = measure.noteRange.end;

					if (t === 0)
						system.measureIndices.push([measure.noteRange.end, measure.index]);
				});

				staff.markings = [];
				staff.yRoundOffset = 0;

				const line = staff.tokens.find(token => token.is("STAFF_LINE"));
				if (line)
					staff.yRoundOffset = line.y - line.ry;
			});

			rowMeasureIndex += Math.max(...system.staves.map(staff => staff.measures.length));
		});
	}


	updateMatchedTokens (matchedIds: Set<string>) {
		this.systems.forEach(system => {
			system.staves.forEach(staff =>
				staff.measures.forEach(measure => {
					measure.matchedTokens = measure.tokens.filter(token => token.href && matchedIds.has(token.href));

					if (!staff.yRoundOffset) {
						const token = measure.matchedTokens[0];
						if (token)
							staff.yRoundOffset = token.y - token.ry;
					}
				}));
		});
	}


	addMarking (systemIndex: number, staffIndex: number, data: Partial<SheetMarkingData>): SheetMarking {
		const system = this.systems[systemIndex];
		if (!system) {
			console.warn("system index out of range:", systemIndex, this.systems.length);
			return;
		}

		const staff = system.staves[staffIndex];
		if (!staff) {
			console.warn("staff index out of range:", staffIndex, system.staves.length);
			return;
		}

		const marking = new SheetMarking(data);
		staff.markings.push(marking);

		return marking;
	}


	removeMarking (id: string) {
		this.systems.forEach(system => system.staves.forEach(staff =>
			staff.markings = staff.markings.filter(marking => marking.id !== id)));
	}


	clearMarkings () {
		this.systems.forEach(system => system.staves.forEach(staff => staff.markings = []));
	}


	toJSON (): object {
		return {
			__prototype: "SheetDocument",
			pages: this.pages,
		};
	}


	getLocationTable (): MeasureLocationTable {
		const table = {};

		this.systems.forEach(system => system.staves.forEach(staff => staff.measures.forEach(measure => {
			measure.tokens.forEach(token => {
				if (token.href) {
					const location = token.href.match(/\d+/g);
					if (location) {
						const [line, column] = location.map(Number);
						table[line] = table[line] || {};
						table[line][column] = Number.isFinite(table[line][column]) ? Math.min(table[line][column], measure.index) : measure.index;
					}
					else
						console.warn("invalid href:", token.href);
				}
			});
		})));

		return table;
	}


	lookupMeasureIndex (systemIndex: number, x: number): number {
		const system = this.systems[systemIndex];
		if (!system || !system.measureIndices)
			return null;

		const [_, index] = system.measureIndices.find(([end]) => x < end) || [null, null];

		return index;
	}


	tokensInSystem (systemIndex: number): StaffToken[] {
		const system = this.systems[systemIndex];
		if (!system)
			return null;

		return system.staves.reduce((tokens, staff) => {
			const translate = token => token.translate({x: staff.x, y: staff.y});

			tokens.push(...staff.tokens.map(translate));
			staff.measures.forEach(measure => tokens.push(...measure.tokens.map(translate)));

			return tokens;
		}, [...system.tokens]);
	}


	tokensInPage (pageIndex: number, {withPageTokens = false} = {}): StaffToken[] {
		const page = this.pages[pageIndex];
		if (!page)
			return null;

		return page.systems.reduce((tokens, system) => {
			tokens.push(...this.tokensInSystem(system.index).map(token => token.translate({x: system.x, y: system.y})));
			return tokens;
		}, withPageTokens ? [...page.tokens] : []);
	}


	fitPageViewbox ({margin = 5, verticalCropOnly = false, pageTokens = false} = {}) {
		if (!this.pages || !this.pages.length)
			return;

		const svgScale = this.pageSize.width / this.pages[0].viewBox.width;

		this.pages.forEach((page, i) => {
			const rects = page.systems.filter(system => Number.isFinite(system.x + system.width + system.y + system.top + system.bottom))
				.map(system => [system.x, system.x + system.width, system.y + system.top, system.y + system.bottom ]);

			const tokens = this.tokensInPage(i, {withPageTokens: pageTokens}) || [];
			const tokenXs = tokens.map(token => token.x).filter(Number.isFinite);
			const tokenYs = tokens.map(token => token.y).filter(Number.isFinite);
			//console.debug("tokens:", i, tokens, tokenXs, tokenYs);

			if (!rects.length)
				return;

			const left = Math.min(...rects.map(rect => rect[0]), ...tokenXs);
			const right = Math.max(...rects.map(rect => rect[1]), ...tokenXs);
			const top = Math.min(...rects.map(rect => rect[2]), ...tokenYs);
			const bottom = Math.max(...rects.map(rect => rect[3]), ...tokenYs);

			const x = verticalCropOnly ? page.viewBox.x : left - margin;
			const y = (verticalCropOnly && i === 0) ? page.viewBox.y : top - margin;
			const width = verticalCropOnly ? page.viewBox.width : right - left + margin * 2;
			const height = (verticalCropOnly && i === 0) ? bottom + margin - y : bottom - top + margin * 2;

			page.viewBox = {x, y, width, height};

			page.width = (page.viewBox.width * svgScale).toString();
			page.height = (page.viewBox.height * svgScale).toString();
		});
	}


	getTokensOf (symbol: string): StaffToken[] {
		return this.systems.reduce((tokens, system) => {
			system.staves.forEach(staff => staff.measures.forEach(measure =>
				tokens.push(...measure.tokens.filter(token => token.is(symbol)))));

			return tokens;
		}, []);
	}


	getNoteHeads (): StaffToken[] {
		return this.getTokensOf("NOTEHEAD");
	}


	getNotes (): StaffToken[] {
		return this.getTokensOf("NOTE");
	}


	getTokenMap (): Map<string, StaffToken> {
		return this.systems.reduce((tokenMap, system) => {
			system.staves.forEach(staff => staff.measures.forEach(measure => measure.tokens
				.filter(token => token.href)
				.forEach(token => tokenMap.set(token.href, token))));

			return tokenMap;
		}, new Map<string, StaffToken>());
	}


	findTokensAround (token: StaffToken, indices: number[]): StaffToken[] {
		const system = this.systems[token.system];
		if (system) {
			const tokens = [
				...system.tokens,
				...cc(system.staves.map(staff => [
					...staff.tokens,
					...cc(staff.measures.map(measure => measure.tokens)),
				])),
			];

			return tokens.filter(token => indices.includes(token.index));
		}

		return null;
	}


	findTokenAround (token: StaffToken, index: number): StaffToken {
		const results = this.findTokensAround(token, [index]);
		return results && results[0];
	}


	alignTokensWithNotation (notation: LilyNotation.Notation, {partial = false, assignFlags = false} = {}) {
		const shortId = (href: string): string => href.split(":").slice(0, 2).join(":");

		const noteTokens = this.getNotes();
		const tokenMap = noteTokens.reduce((map, token) => {
			const sid = token.href && shortId(token.href);
			const tokens = map.get(sid) || [];

			// shift column for command chord element
			if (/^\\/.test(token.source)) {
				const spaceCapture = token.source.match(/(?<=\s+)(\S|$)/);
				if (spaceCapture) {
					const [line, column] = token.href.match(/\d+/g).map(Number);
					map.set(`${line}:${column + spaceCapture.index}`, [token]);

					return map;
				}
				else
					console.warn("unresolved command chord element:", token.source, token);
			}

			tokens.push(token);
			token.href && map.set(sid, tokens);

			return map;
		}, new Map<string, StaffToken[]>());
		//console.assert(tokenMap.size === noteTokens.length, "tokens noteTokens count dismatch:", tokenMap.size, noteTokens.length);

		const tokenTickMap = new Map<StaffToken, {measureTick: number, tick: number}>();

		// assign tick & track
		notation.measures.forEach((measure, mi) => {
			const pendingStems = new Map<StaffToken, StaffToken>();	// stem -> beam

			measure.notes.forEach(note => {
				const tokens = tokenMap.get(shortId(note.id));
				if (tokens) {
					tokens.forEach(token => {
						token.href = note.id;
	
						if (!Number.isFinite(token.tick)) {
							tokenTickMap.set(token, {measureTick: measure.tick, tick: measure.tick + note.tick});
							token.pitch = note.pitch;
							token.track = note.track;

							if (token.stems) {
								const stems = this.findTokensAround(token, token.stems);
								if (stems) {
									const stem = stems.find(stem => stem.division === note.division && !Number.isFinite(stem.track));
									if (stem) {
										stem.track = note.track;

										if (stem.beam >= 0) {
											const beam = this.findTokenAround(stem, stem.beam);
											if (stems.length < 2 || stems[0].division !== stems[1].division)
												beam.track = stem.track;
										}
									}
									else if (!stems.find(stem => stem.division === note.division))
										console.warn("missed stem:", mi, token.href, note.division, token.stems, stems.map(stem => stem.division));

									stems.forEach(stem => {
										tokenTickMap.set(stem, {measureTick: measure.tick, tick: measure.tick + note.tick});
										if (stems.length > 1 && stem.beam >= 0) {
											const beam = this.findTokenAround(stem, stem.beam);
											if (beam)
												pendingStems.set(stem, beam);
										}
									});
								}
								else
									console.warn("stems token missing:", token.system, token.stems, mi, token.href);
							}
						}
					});
				}
				else if (!partial)
					note.overlapped = true;
			});

			//if (pendingStems.size)
			//	console.log("pendingStems:", mi, [...pendingStems].map(s => s.index));
			for (const [stem, beam] of pendingStems) {
				if (Number.isFinite(beam.track))
					stem.track = beam.track;
			}
		});

		const tokenTickMapKeys = Array.from(tokenTickMap.keys());
		this.systems.forEach(system => {
			system.staves.forEach(staff => staff.measures.forEach(measure => {
				const tokens = measure.tokens.filter(token => tokenTickMapKeys.includes(token));
				const meastureTick = tokens.reduce((tick, token) => Math.min(tokenTickMap.get(token).measureTick, tick), Infinity);
				tokens.forEach(token => token.tick = tokenTickMap.get(token).tick - meastureTick);
			}));
		});

		if (assignFlags)
			this.assignFlagsTrack();
	}


	assignFlagsTrack () {
		const flags = this.getTokensOf("FLAG");
		flags.forEach(flag => {
			if (Number.isFinite(flag.stem)) {
				const stem = this.findTokenAround(flag, flag.stem);
				if (stem && Number.isFinite(stem.track))
					flag.track = stem.track;
			}
		});
	}


	pruneForBakingMode () {
		const round = x => roundNumber(x, 1e-4);

		this.pages.forEach(page => {
			page.tokens = [];

			page.systems.forEach(system => {
				system.tokens = [];
				system.measureIndices = system.measureIndices && system.measureIndices.map(([x, i]) => [round(x), i]);

				system.staves.forEach(staff => {
					staff.tokens = [];
					staff.yRoundOffset = round(staff.yRoundOffset);
					delete staff.top;
					delete staff.headWidth;

					staff.measures.forEach(measure => {
						measure.headX = round(measure.headX);
						measure.lineX = round(measure.lineX);
						measure.noteRange = {
							begin: round(measure.noteRange.begin),
							end: round(measure.noteRange.end),
						};

						measure.tokens = measure.matchedTokens.map(token => new StaffToken(pick(token, [
							"x", "y", "symbol", "href", "scale", "tied",
						])));
						delete measure.matchedTokens;
					});
				});
			});
		});
	}


	appendLinkedTokensForStaves (): void {
		const doneTokens = new Set();
		const appendLink = (staff: SheetStaff, oldStaff: SheetStaff, token: StaffToken): void => {
			if (doneTokens.has(token.index))
				return;
			//console.log("appendLink:", staff, oldStaff, token);
			const dy = staff.y - oldStaff.y;

			const measure = staff.measures.find(measure => measure.noteRange.end >= token.x);
			if (measure) {
				const newToken = new StaffToken({...token, symbols: new Set(), y: token.y - dy, ry: token.ry - dy});
				token.addSymbol("ACROSS_STAVES");
				newToken.addSymbol("ACROSS_STAVES");
				newToken.addSymbol("DUPLICATED");
				measure.tokens.push(newToken);
			}
			else
				console.warn("appendLink failed, because no fit measure:", staff.measures, token);

			doneTokens.add(token.index);
		};

		this.pages.forEach(page => {
			const tokens: StaffToken[] = (page.systems
				.map(system => system.staves
					.map(staff => staff.measures
						.map(measure => measure.tokens))) as any).flat(3);
			const tokenStaffTable: Record<number, SheetStaff> = page.systems
				.reduce((table, system) => system.staves
					.reduce((table, staff) => staff.measures
						.reduce((table, measure) => measure.tokens
							.reduce((table, token) => {
								table[token.index] = staff;
								return table;
							}, table), table), table), {});

			//console.log("tokenStaffTable:", tokenStaffTable);

			tokens.forEach(token => {
				if (token.stems) {
					const staff = tokenStaffTable[token.index];
					token.stems.forEach(stem => {
						if (tokenStaffTable[stem] !== staff)
							appendLink(tokenStaffTable[stem], staff, token);
					});
				}
			});
		});
	}
};



export default SheetDocument;