import { BidiModule, Direction } from '@angular/cdk/bidi';
import { Component, DestroyRef, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { RouterOutlet } from '@angular/router';
import { InConfiguration } from 'src/app/core/models/config.interface';
import { DirectionService } from 'src/app/core/service/direction.service';
import { ConfigService } from 'src/app/config/config.service';
import { HeaderComponent } from '../../header/header.component';
import { SidebarComponent } from '../../sidebar/sidebar.component';
import { RightSidebarComponent } from '../../right-sidebar/right-sidebar.component';

@Component({
	selector: 'app-main-layout',
	templateUrl: './main-layout.component.html',
	styleUrls: [],
	standalone: true,
	imports: [BidiModule, RouterOutlet, HeaderComponent, SidebarComponent, RightSidebarComponent],
})
export class MainLayoutComponent {
	direction!: Direction;
	config!: InConfiguration;
	private readonly destroyRef = inject(DestroyRef);

	constructor(
		private directoryService: DirectionService,
		private configService: ConfigService
	) {
		this.config = this.configService.configData;
		this.directoryService.currentData
			.pipe(takeUntilDestroyed(this.destroyRef))
			.subscribe((currentData) => {
				if (currentData) {
					this.direction = currentData === 'ltr' ? 'ltr' : 'rtl';
				} else {
					if (localStorage.getItem('isRtl')) {
						if (localStorage.getItem('isRtl') === 'true') {
							this.direction = 'rtl';
						} else if (localStorage.getItem('isRtl') === 'false') {
							this.direction = 'ltr';
						}
					} else {
						if (this.config) {
							if (this.config.layout.rtl === true) {
								this.direction = 'rtl';
								localStorage.setItem('isRtl', 'true');
							} else {
								this.direction = 'ltr';
								localStorage.setItem('isRtl', 'false');
							}
						}
					}
				}
			});
	}
}
